Name: dbT83986 Date: 02/25/99
The code below causes two equal() objects to be added
to a HashSet. Turns out the problem is that I did not
override hashCode for the class---under Object.hash()
the two objects are mapped into separate buckets,
and the equals test is never made.
This is probably not a bug technically, since the documentation
for Object.hashCode() does specify that if two objects are
equals(), then they must produce the same hash value. However,
this requirement is not mentioned in the documentation for
equals(), nor in the documentation for HashSet. So the
documentation doesn't do you any good until you have already
solved the problem.
//****************************************************
import java.util.*;
import java.io.*;
public final class Test extends Object {
private String value;
public Test (String ss) {
value = ss;
}
public String toString() {
return value.toString();
}
public boolean equals (Object dbv) {
if (dbv.getClass() != this.getClass())
return false;
else { return value.equals(((Test) dbv).value); }
}
public static void main(String argv[]) {
HashSet hs = new HashSet();
Test s1 = new Test("1");
Test s2 = new Test("1");
hs.add(s1);
hs.add(s2);
System.out.println(hs);
}
}
(Review ID: 48699)
======================================================================
- duplicates
-
JDK-4505332 Equals method doc needs reference to hashCode in Object class
-
- Closed
-