List list = new ArrayList();
list.add(12);
System.out.println(list);//输出 [12]
如上,我们都知道,List、Set 继承了Collection集合,输出[12],是因为重写了toString,
但是toStringn你知道是具体在那实现的吗?
让我们先来看一下他们的继承结构:
原来是在AbstractCollection类中重写了toString方法,源码如下:
/**
* 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(' ');
}
}