Java prints object addresses to prevent Recursion

Source: Internet
Author: User

1. as followsCode: Use the this keyword to print the object address

 

Import java. util .*;
Public class infiniterecursion {
 
Public String tostring (){
 
Return "infiniterecursion address:" + This + "\ n ";
// Return "infiniterecursion address:" + super. tostring () + "\ n ";
}

Public static void main (string [] ARGs ){
List <infiniterecursion> V = new arraylist <infiniterecursion> ();
For (INT I = 0; I <1; I ++)
V. Add (New infiniterecursion ());
System. Out. println (v );
}
}///:~

Result: recursive tostring () method.

Explanation:

 

The compiler sees a string followed by a '+', but the object after '+' is not a string, so the compiler tries

Convert to the string type. This type of conversion operation calls the tostring () method and generates a recursive call.

In this example, if you really want to print the object address, you should call the tostring () method of the object.

Do this. Therefore, replace this with super. tostring.

 

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.