File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes equals() and hashCode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "equals() and hashCode()" Watch "equals() and hashCode()" New topic
Author

equals() and hashCode()

Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77
I do not understand why the behavior is different.



SCJP 1.4
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

What behaviour is that? And what is it different from, and in what way?
Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77
Firstly you get:
null
2

Secondly you get:
Y
1

Obviously the first output is false. The only difference is, that you do not override the method hashCode().
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

Which explains what it says in the API documentation for Object:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Since you are implicitly using the hashCode method by putting your objects into a HashMap, you should follow this rule. And since you are getting unexpected results, perhaps you didn't follow this rule. That would mean that you have created two objects which are "equal" but have different hashCode values; you could check that with a little debugging.

And your second (correct) example has a hashCode method which does follow that rule, and so you get correct-looking results.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

HashSet, HashMap etc first use the return value of hashCode() to find the "bucket" the object is in. After that it uses equals to check all elements inside the bucket. If hashCode() does not follow the contract then the HashSet / HashMap will look in the wrong bucket.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals() and hashCode()