The ToString () method in the collection object
1. Code:
public class Test {
public static void Main (string[] args) {
Collection<string> c=new arraylist<string> ();
C.add ("Hello");
C.add ("World");
C.add ("Java");
System.out.println (c);
}
}
Output Result:
[Hello, World, Java]
2. Question: Why is the result of direct output not an address value?
In fact collection<string> c=new arraylist<string> (); This is polymorphic, the output is the ToString () method of C, in fact the output is ArrayList ToString ()
So let's look at the ToString () method of ArrayList, but we don't find the relevant ToString () method in ArrayList, so we go to the parent class to find
, we find that there is.
3.toString () method source code
Public String toString () {
The collection itself calls the iterator method to get the iterator collection
Iterator<e> it =iterator ();
if (!it.hasnext ())
Return "[]";
StringBuilder sb=new StringBuilder ();
Sb.append ("[");
Unconditional cycle of death
for (;;) {
E E=it.next ();
Sb.append (e==this? "(This Collection)": E);
if (!it.hasnext ())
Return Sb.append ('] '). toString ();
Sb.append ('] '). Append (');
}
}
With the above code, we can see that the ToString () method means that 2 is the concatenation of the string, and then it iterates over the case to get an array call to the ToString () method output.
The ToString () method of the Java base _ collection