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?
A Set is a Collection that cannot contain duplicate elements.
No, it never returns true unless you feed it the same exact object reference. The reason for it is that Java objects are not "embedded" in one another: there is a reference to B inside A , but it refers to a completely different object.
var result = first. add(second); Write a Number class with a constructor that takes an int. Write an add method that returns a new number object and you're good to go.
public int hashcode() {
return this.getId().hashCode();
}
should be
@Override
public int hashCode() {
return this.getId().hashCode();
}
The annotation would have told you about the spelling mistake.
There should also be a (missing) little triangle symbol in your IDE on the method to indicate if an interface is being implemented or a parent method overridden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With