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. 128
Choosing a “good”
hashCode()
method
Q: |
We consider:
Which of the two
TipExcerpt from
|
||||
A: |
According to Figure 415, “Hashing in Java and
A so called perfect
Combining these two statements a perfect hashCode() method will have the following property:
Method 1 serves this purpose: Its returns a given
Conclusion: Whenever two instances of
This does not hold with respect to method 2. Consider two
instances (1 hour, 2 minutes, 3 seconds) vs. (3 hours, 2 minutes,
1 second) returning an identical
NotePerfect hash functions are rare with respect to real world
modeling problems. In the current example
|
No. 129
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: |
It is not possible to construct a perfect hashCode() method
acting on strings. A Java
Thus considering just the union of zero (empty), one- and
two character strings we have
possibilities exceeding the
count of different The JDK™'s String.hashCode() implementation already reveals conflicts for ASCII strings of length 2:
|