Collection中的List,Set的toString()方法

代码:
    Collection c = new ArrayList();
    c.add("hello");
    c.add("world");
    c.add("java");
   
    System.out.println(c);
   
为什么c输出的不是地址值呢?
    A:Collection c = new ArrayList();
        这是多态,所以输出c的toString()方法,其实是输出ArrayList的toString()
    B:看ArrayList的toString()
        而我们在ArrayList里面却没有发现toString()。
        以后遇到这种情况,也不要担心,你认为有,它却没有,就应该去它父亲里面看看。
    C: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();
    }
原文地址:https://www.cnblogs.com/qq-757617012/p/4285529.html