The ToString () method of the Java base _ collection

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.