I would like to know what happens when two objects equal according to equals() are used as keys in order to store values into a HashMap.
1. Does it make sense to do that?
2. What happens when one tries to put the second key/value into the HashMap?
3. What happens when one tries to get the second key from the HashMap?
Any comment welcome,
Thanks for your replies and sorry: I missed an important bit of information in my question.
I meant to say: What happens when two objects whose hashCode method has not been overriden and therefore inherit the hashcode method from Object and are equal according to equals() are used as keys in order to store values into a HashMap.
1. What happens when one tries to put the second key/value into the HashMap?
My answer: it works fine insofar as the hashcode method from Object returns a unique id.
2. What happens when one tries to get the second key from the HashMap?
This is where your comments are welcome.
You'll always learn more by experimenting than just being told the answer.
Joanne, I do know experimenting is a good way to learn. However sometimes exchanging with others can be stimulating and interesting as well...
The two keys will probably not be seen as equals. HashMap and Hashtable use buckets, and the hash code is used to determine in which bucket an object is placed. So if the hash codes are different the keys will be put / looked for in different bucket. This is the very reason why the equals and hashCode method are so tightly coupled.
It depends whether you have a hash code collision. If you get both keys into the same bucket, because the lower-significance bits in their hash codes (in binary) happen to be the same, then they will behave as if they were the same object. Otherwise they will behave (I would have thought) as different objects.
I would remind any greenhorns reading this thread:
This practice is incorrect because the hashCode method ought to be overridden along with equals(), but this is obviously permissible in this case because it is simply a "What-if?" application which will never be released into the "wild".