Understanding the rewriting of tostring () and hashcode () Methods

Source: Internet
Author: User
Generally, the tostring () method is applied to its own Bean class. Organize the information of the current object you want to display in the override tostring method as needed. For example, the attribute name and value are returned in a certain rule format. When you want to read some useful details about an object, you can call tostring () on the object (). For example, when an object is referenced to system. Out. println ();, the tostring () method of the object is called. All classes in Java inherit from the object parent class. Therefore, we only need to override the tostring () method in the class to display the information we want. See the following example:
Public class overridetostring {Public String tostring () {return "this is overridetostring! ";}}

 

We have rewritten the tostring method above. Now let's test it:
Public class testoverridetostring {public static void main (string [] ARGs) {overridetostring OTs = new overridetostring (); system. Out. println (OTs );}}

 

The output result is: This is overridetostring! Rewriting tostring is a format for printing and outputting objects. When the output operation is performed, Java calls tostring. When the hash operation is involved, Java calls the hashcode method to compare the returned values.

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.