Skip to content
Sharp

Core Java · interview question

Why is it a bad practice to use mutable fields in equals and hashCode implementations?

Multiple choiceMediumchapter-4-curatedpremiumcore-javaequals-and-hashcode-in-collections
Choose one answer
Answer and explanation

Correct answer

C. Mutable fields can change and lead to inconsistent behavior in collections.

Why

Using mutable fields in equals and hashCode methods can lead to inconsistent behavior because the object’s hash code might change when the mutable field changes, causing the object to be 'lost' in hash-based collections. This violates the contract that the hash code should remain consistent during an object's lifetime.

Test yourself on Core Java

A free test with instant, explained results. No account needed.

Start free test
All Core Java questions →