Home » Uncategorized

Java toString() can be misleading

4 May 2005 849 Views One Comment

If you’ve ever done a toString on an object that doesn’t override toString(), you’ve probably noticed that it returns something like this.

com.mycode.MyClass@1312311

Now the big question: can two different object instances ever have the same value after the ‘at’ (@) sign?

The answer is yes. If you look at the source for Java’s Object class, the toString() method prints the name of the class, the @, and the value of the hashCode() method. If your class overrides hashCode(), and you create two objects that have the same exact hash code (because all of their values are identical), then you can reproduce this behavior.

I’ve always naively assumed that the number after the @ was always the object’s memory address in the heap.

One Comment »

  • Anonymous said:

    thanx you have just solved an existenzial problem!

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.