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 On not overriding hashCode() and the usability of the class as a key in a HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "On not overriding hashCode() and the usability of the class as a key in a HashMap" Watch "On not overriding hashCode() and the usability of the class as a key in a HashMap" New topic
Author

On not overriding hashCode() and the usability of the class as a key in a HashMap

Steven Squeers
Ranch Hand

Joined: Aug 19, 2013
Posts: 62
Hi,
In Bates/Sierra there is a question about (inter alia) a class (call it X) that doesn't override hashCode(). Of the possible answers to the question "If instances of class X are to be used as keys in a Map, which are true?", where class X doesn't override hashCode(), this answer is stated as correct:

C. It’s possible for such keys to find the correct entries in the Map.

I thought, you couldn't say this, because
1. Object.hashCode() uses a pseudo memory address. Therefore 2 objects with the same state would have 2 different hashCodes. Also,
2. for any instance o of X, if you put it in a HashMap, serialize it (i.e. o) and deserialize it, won't the hashMap hashCode of the deserialized o be different? Therefore when you try to find it in the HashMap it won't be found?

Is my understanding on either or both of these points wrong?

Thanks in advance.


Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Both your points are true in general, almost always. However it's possible that the hashcode will end up the same. Furthermore, it's even more possible that different hashcodes will nonetheless end up in the same bucket in the hashmap (where bucket index is calculated as hashcode % mapsize) which will allow the requested key to be found, even if it doesn't have a properly overridden hashcode. so yes, it's possible the map will work. It is however unlikely that it will work, and failing to override hashCode() in this case is a very bad practice.
Steven Squeers
Ranch Hand

Joined: Aug 19, 2013
Posts: 62
Mike, that helps, thanks very much.

SS
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: On not overriding hashCode() and the usability of the class as a key in a HashMap