2014-06-25 41 views
0
Collection col=new ArrayList(); 
col.add("a"); 
col.add("b"); 
System.out.println(col); 

toString()方法未在java.util.collection包中被覆蓋時,如何打印集合對象打印其所有內容?集合不重寫toString()時如何打印Collection子類的內容?

+2

你知道多態? –

+2

ArrayList的擴展'java.util.AbstractCollection'這確實覆蓋'的toString()'方法 –

+0

記住同級車實際上不是'Collection'它仍然是一個'ArrayList' –

回答

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