java hash tables
Misunderstanding of behavior of Hashtable in java 6?
I am getting some very strange results when using the Hashtable in java 6.
Here is what I am doing:
1) I create a hash table with a key,pair value. The key is my own object which contains its own equals method.
2) I add key,pair values successfully
3) However, when I attempt to retrieve a key pair value by Hashtable.get( key ) it will only work if I use the ‘exact’ key object that I inserted into the hash table using Hashtable.put(key,value). If I use a different ‘version’ of the key, even though my equals method says that the keys are ‘equal’ it will still return a null (not found).
The java 6 documentation however says that Hashtable will return a value if the given key.equals a key entry in the Hashtable.
What is happening here? Any ideas?
If your class overrides the equals() method, it should also override the hashCode() method. Your hashCode() method should be written in a way that guarantees that two objects that compare equal also produce the same hash value. If you forget to do this then you’ll get exactly the kind of weirdness that you’re seeing.
CS 61B Lecture 15: More Java