After adding two identical objects to a Set, I would expect the set to contain only one element.
public void addIdenticalObjectsToSet(){
Set<Foo> set = new HashSet<Foo>();
set.add(new Foo("totoro"));
set.add(new Foo("totoro"));
Assert.assertEquals(1, set.size()); // PROBLEM: SIZE=2
}
private class Foo {
private String id;
public Foo(String id) {
this.id = id;
}
public String getId() {
return id;
}
public boolean equals(Object obj) {
return obj!= null && obj instanceof Foo &&
((Foo)obj).getId().equals(this.getId());
}
public int hashcode() {
return this.getId().hashCode();
}
}
I consider two objects as identical if they have the same id (String).
Other strange thing: Neither Foo.equals nor Foo.hashcode are accessed, as far as I can tell using debug/breakpoints. What am I missing?