The problem you will have is with collections where unicity of elements is calculated according to both .equals()
and .hashCode()
, for instance keys in a HashMap
.
As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode()
.
If you have two objects which are .equals()
, but have different hash codes, you lose!
The part of the contract here which is important is: objects which are .equals()
MUST have the same .hashCode()
.
This is all documented in the javadoc for Object
. And Joshua Bloch says you must do it in Effective Java. Enough said.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…