Objects, equals() and hash-values
-
Where is the blond haired guy?
-
I take the pink flower.
-
The 334.50$ cellular phone.
Method hashCode()
:
Instance 0 ⇨ o.hashCode()
, of type int
.
-
Same value on repeated invocation
-
Objects with identical value with respect to
equals()
must have identical hash values:true == a.equals(b)
⟹a.hashCode() == b.hashCode()
. -
Conversely: Two instances differing with respect to
equals()
may have identical hash values.
Consequence: equals()
and
hashCode()
must be redefined simultaneously!
public class Rectangle { int width, height; @Override public boolean equals(Object o) { if (o instanceof Rectangle r) { return width == r.width && height == r.height; } else { return false; } } @Override public int hashCode() { return width + height; } }
public class Rectangle {
int width, height;
...
@Override public int hashCode() {
return width + height;
}
} |
width | height | hash value |
---|---|---|---|
1 | 3 | 4 | |
2 | 2 | 4 | |
5 | 5 | 10 | |
2 | 7 | 9 | |
4 | 9 | 13 |
public class Rectangle {
int width, height;
...
@Override public int hashCode() {
return width + 13 * height;
}
} |
width | height | hash value |
---|---|---|---|
1 | 3 | 40 | |
2 | 2 | 28 | |
5 | 5 | 70 | |
2 | 7 | 93 | |
4 | 9 | 121 |
No. 135
Choosing a “good”
hashCode()
method
Q: |
We consider: public class TimePeriod { private final int hours, minutes, seconds; /** * A time period within a day e.g. 4 hours, 23 minutes and 11 seconds. * * @param hours Hours ranging from 0 to 23 * @param minutes Minutes ranging from 0 to 59 * @param seconds Seconds ranging from 0 to 59 */ public TimePeriod(final int hours, final int minutes, final int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } @Override public boolean equals(final Object o) { if (o instanceof TimePeriod t) { return hours == t.hours && minutes == t.minutes && seconds == t.seconds; } else { return false; } } } Which of the two
TipExcerpt from
|
||||
A: |
No. 136
String
and good hashCode()
implementations.
Q: |
In the previous exercise we found a perfect
Does a perfect hash function exist for String instances as well? TipConsider the possible number of different strings. |
A: |