如果集合没有覆盖toString(),那么如何打印Collection子类内容?

时间:2014-06-25 15:31:24

标签: java tostring

Collection col=new ArrayList();
col.add("a");
col.add("b");
System.out.println(col);

如果在toString()包中没有覆盖java.util.collection方法,那么如何打印集合对象会打印其所有内容?

1 个答案:

答案 0 :(得分:6)

来自AbstractCollection的ArrayList扩展...

/**
 * 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(' ');
    }
}