java中这句话调用谁的toString方法?

来源:百度知道 编辑:UC知道 时间:2024/05/19 19:10:04
import java.util.*;
public class Test {
public static void main(String [] args) {
Collection c = new ArrayList();
c.add("hello");
c.add(new Integer(100));
System.out.println(c);
}
}
最后打印的结果是[hello, 100]
我很晕,查api文档查了半天,Collection,ArrayList都没发现谁重写了Object的toString方法,为什么打印的结果会这样???????

ArrayList继承了AbstractList这个类;
AbstractList又继承了AbstractCollection类
AbstractCollection是ArrayList的爷爷类咯

AbstractCollection就重写了toString方法:

public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[");

Iterator<E> i = iterator();
boolean hasNext = i.hasNext();
while (hasNext) {
E o = i.next();
buf.append(o == this ? "(this Collection)" : String.valueOf(o));
hasNext = i.hasNext();
if (hasNext)
buf.append(", ");
}

buf.append("]");
return buf.toString();
}

ArrayList从AbstractCollection类继承了toString方法.

它是Object的子类,当然可以调用Object的toString方法,继承父类的所有

请参见:
abstractCollection 源码src

public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())