Object-oriented programming · interview question
Which statements about the equals/hashCode contract are true? Select all that apply.
Select all that applyMedium
Answer and explanation
Correct answer
- A. If
a.equals(b)is true, thena.hashCode() == b.hashCode()must be true. - C. Overriding
equalswithouthashCodebreaks lookups inHashMapandHashSet. - D.
equalsmust be symmetric:a.equals(b)impliesb.equals(a).
Why
Hash-based collections find the bucket by hashCode, then compare with equals. Equal objects with different hash codes land in different buckets and can't be found.
References
- Joshua Bloch, Effective Java, 3rd ed. (2018)
- Java SE 21 API documentation
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- What issue might arise if a constructor directly assigns a mutable object without copying it?
- What happens if a subclass does not implement all abstract methods from its abstract superclass?
- What does the 'this' keyword refer to within an instance method of a class?
- Which Java keyword would you use to declare an abstract class in Java?
- Which statement correctly creates an instance of the 'Product' class?
- How does using interfaces in Java promote flexibility in application design?