The tostring__list of the collection in traced Java

Source: Internet
Author: User
first, there is a problem:

list<string> list = new arraylist<string> ();
List.add ("Zhangsan");
List.add ("Lisi");
SYSTEM.OUT.PRINTLN (list);
So what's the result of this printing?

[Zhangsan, Lisi]

So the question came, ' [] ' where it came from.

We know that all objects do not output the object's information until they have overridden the ToString () method of the object class. Otherwise the output would be something like cn.edu.lnu.test.box@15db9742, what it is. Is class ' All class name @hashcode ', we look at the source code of object:

Package Java.lang;

/**
 * Class {@code Object} is the root of the class hierarchy.
 * Every class has {@code Object} as a superclass. All objects,
 * including arrays, implement the methods of this class.
 * *
 @author  unascribed
 * @see     java.lang.Class *
 @since   JDK1.0
* * Public Class Object {public
    native int hashcode ();
    Public String toString () {return
        getclass (). GetName () + "@" + integer.tohexstring (Hashcode ());
    }
From this, we can conclude that a custom class can only print out the contents of an object only if it overrides the object's ToString () method.

So we guess: The list interface definitely rewrites the object's ToString (), and goes to see the source code and finds:

there is no ...


What the hell is going on?

look at the relationship of the collection in Java, the diagram above:





It turns out that Abstractcollection has rewritten the ToString () method. At this point, all the fog has been opened.

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.