Situation
I needed to overwrite equals()
, and as recommended, I also overwrite the method hashCode()
using the same fields. Then, when I looked at a set containing only one object, I got a disappointing result
set.contains(object)
=> false
and
set.stream().findFirst().get().equals(object)
=> true
Now I understand that this is due to changes made to object
after it was added to set
, which again changed its hashCode. contains
then it looks through the wrong key and cannot find it object
.
My implementation requirements:
- For correct implementation
equals()
mutable fields are needed to safely use these objects in hash-based Collections
or Maps
such ashes HashSet
, even if they are subject to change.which conflicts with the agreement that
Question
Are there any dangers for using only the subset of the fields that are used equals()
to calculate hashCode()
instead of using all?
More specifically, this would mean: it equals()
uses several fields of the object, while it hashCode()
uses only those fields that are used in and which are immutable . equals()
I think it should be good, because
- : -, hashCode , .
- - ,
HashSet
.
, , : hashCode Java? equals hashcode