In Java, every object has an equals and a hashCode method that is used, among ot
ID: 3562290 • Letter: I
Question
In Java, every object has an equals and a hashCode method that is used, among other things,
by the standard Collections library. By default both are based on an object's memory location, but best
practice dictates that they should be overridden to be dependant on the object's state. The rule that
should be followed when doing this is: if two objects are equal, then they should have the same hash
code value. Which of the following situations would be permissible and which would not under this rule?
Provide a brief justi?cation.
(a) Two objects have the same hash code and are equal
(b) Two objects are equal but have di?erent hash codes
(c) Two objects have the same hash code but are not equal
(d) Two objects have di?erent hash codes and are not equal
Explanation / Answer
If two objects have the same hashcode then they are NOT necessarily equal. But the opposite is true - if the objects are equal ,then they must have the same hashcode.
Hence (a) is false.
Considering the above (b) is also false.
hashcode () is a function to generate hash by some formula, so there can be some collisions, two different values can turn out to have same hashcode. But not always..Hence (c) and (d) both are true condition.
Remember
"Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes."
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.