Java FPT Software (Fsoft) Academy Practice Test

Access More Questions
Which statement accurately reflects the equals/hashCode contract?
Correct Answer:
If two objects are equal according to equals(), their hashCode must be equal
Explanation:
In Java, objects that are considered equal by the equals method must produce the same value from hashCode. This alignment is essential for hash-based collections like HashMap and HashSet to find and retrieve elements reliably. If two equal objects could have different hash codes, they would end up in different buckets, making lookups unpredictable or incorrect. Hash codes are used for hashing, not for sorting. Sorting relies on comparisons (like compareTo or a Comparator), while hashing relies on the hashCode value to bucket objects. If you override equals, you should also override hashCode to maintain this contract. It doesn’t matter whether the objects are mutable; what matters is consistency: objects that are equal must always yield the same hash code. If the fields involved in determining equality change after an object is placed in a hash-based collection, it can become unreachable or misplaced unless you carefully manage mutations.

Access more questions from this quiz

Continue to Java FPT Software (Fsoft) Academy Practice Test for more practice questions and the full quiz experience.

Access More Questions