I was messing around trying to understand how HashSets behave and I've run into this problem that I can't get my head around. The 2nd and 3rd dog objects have the same name, and equals()
and hashcode()
have been overriden to make names mean equality. Despite this, the hashSet still has duplicates, and I can't figure out why.
I reread the data structures chapter of Head First Java but it still suggests that my code should work in theory.
public class DataStructsTests<E> {
HashSet<Dogs> tree = new HashSet<Dogs>();
HashSet<Dogs> treeOwner = new HashSet<Dogs>();
public static void main(String[] args) {
DataStructsTests<String> d = new DataStructsTests<String>();
d.go();
}
public void go() {
Dogs dog = new Dogs("Scout", "a");
tree.add(dog);
treeOwner.add(dog);
Dogs dog2 = new Dogs("Brodie", "b");
tree.add(dog2);
treeOwner.add(dog2);
Dogs dog3 = new Dogs("Brodie", "c");
tree.add(dog3);
treeOwner.add(dog3);
System.out.println(tree);
System.out.println(treeOwner);
System.out.println(dog2.equals(dog3));
System.out.println(dog2.hashCode() + " " + dog3.hashCode());
}
class Dogs {
private String name;
private String ownerName;
public Dogs(String n, String o) {
name = n;
ownerName = o;
}
public boolean equals(Dogs d) {
return name.equals(d.getName());
}
public int hashCode() {
return name.hashCode();
}
public String getName() {
return name;
}
public String toString() {
return name;
}
Running the program returns this:
[Brodie, Brodie, Scout]
[Brodie, Brodie, Scout]
true
1998211617 1998211617
Even though equals()
returns true and the hashcodes are the same, the duplicates still remain.
Edit: Turns out the problem was that I hadn't overridden the equals() method properly as I used Dog rather than Object.