20.3 Contains & Duplicate Items
Contains
The equals()
Method for a ColoredNumber Object
equals()
Method for a ColoredNumber ObjectSuppose the equals()
method for ColoredNumber is as below, i.e. two ColoredNumbers are equal if they have the same num.
HashSet Behavior for Checking contains()
contains()
Suppose the equals()
method for ColoredNumber is on the previous slide, i.e. two ColoredNumbers are equal if they have the same num.
Suppose we now check whether 12 is in the hash table.
What do we expect to be returned by contains
?
Finding an Item Using the Default Hashcode
Suppose we are using the default hash function (uses memory address):
which yields the table below:
Suppose equals returns true if two ColoredNumbers have the same num (as we've defined previously).
What is actually returned by contains
?
Hard Question: If the default hash code achieves a good spread, why do we even bother to create custom hash functions?
Basic rule (also definition of deterministic property of a valid hashcode): If two objects are equal, they must have the same hash code so the hash table can find it.
Duplicate Values
Overriding equals()
but Not hashCode()
equals()
but Not hashCode()
Suppose we have the same equals()
method (comparing num
), but we do not override hashCode()
.
The result of adding 0 through 19 is shown below:
Which can happen when we call add(zero)?
Answer Choices:
We get a 0 to bin zero.
We add another 0 to bin one.
We add a 0 to some other bin.
We do not get a duplicate zero
Key Takeaway: equals()
and hashCode()
equals()
and hashCode()
Bottom line: If your class override equals, you should also override hashCode in a consistent manner.
If two objects are equal, they must always have the same hash code.
If you don’t, everything breaks:
Contains
can’t find objects (unless it gets lucky).Add
results in duplicates.
Last updated