Collection col=new ArrayList();
col.add("a");
col.add("b");
System.out.println(col);
当java.util.collection
包中的toString()
方法没有被覆盖时,为什么打印集合对象会打印它的所有内容?
最佳答案
来自 ArrayList 扩展的 AbstractCollection...
/**
* Returns a string representation of this collection. The string
* representation consists of a list of the collection's elements in the
* order they are returned by its iterator, enclosed in square brackets
* (<tt>"[]"</tt>). Adjacent elements are separated by the characters
* <tt>", "</tt> (comma and space). Elements are converted to strings as
* by {@link String#valueOf(Object)}.
*
* @return a string representation of this collection
*/
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
关于java - 当集合没有重写 toString() 时,如何打印集合子类内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24412848/