In this particular case, since the keys (i.e. the two Info objects) are unequal as per their equals() method and even though their hashcode are same, the HashMap will work properly for them. Both the objects will be stored and retrieved. However, the retrieval will fail only for Info objects that break the rule of equals() and hashCode() are put in the map.
Astha - OCPJP 6 (90%)
Astha Sharma wrote:Correct statement-
"Both the objects will be stored in the HashMap however retrieving them using the Info objects as keys will not be possible."
Andrea, andbin.dev — SCJP 5 (91%) – SCWCD 5 (94%)
java.util.function Interfaces Cheat Sheet — Java Versions Cheat Sheet
Astha Sharma wrote:Question from enthuware mock test-
Correct statement-
"Both the objects will be stored in the HashMap however retrieving them using the Info objects as keys will not be possible."
Explanation
In this particular case, since the keys (i.e. the two Info objects) are unequal as per their equals() method and even though their hashcode are same, the HashMap will work properly for them. Both the objects will be stored and retrieved. However, the retrieval will fail only for Info objects that break the rule of equals() and hashCode() are put in the map.
Here I don't understand the line written in bold. What does it mean? It would be great if anyone can give some example of Info objects breaking rule of equals() and hashCode().
OCPJP 6 - 96%
Currently working on Scala at Knoldus Software
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
Himai Minh wrote:Astha,
This is the equals and hash code contract:
1. If two objects have the same hash code, they may or may not be equal.
2. If two objects have different hash codes, they are not equal.
3. If the hash codes of two objects are different, the two objects are not equal.
4. If the hash code of two objects are the same, the two objects may or may not be equal.
Analogy:
We have 10 buckets with a number on each of them : 1, 2, 3 ...10
1. If two balls (red and blue balls) are put in bucket 1, they have the same bucket number (hash code), but they are different balls.
2. If two balls (red and blue balls) are put in bucket 2 and 3, they have different bucket numbers (hash codes), and they are two different balls.
3. If you are looking for a red ball in bucket 1, then you find a red ball. This red ball is the one you are looking for.
4. If you are looking for a ball in bucket 1, you find a red and blue ball. But they are different balls.
hth
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |