I have the following code:
public class MyElement {
String name;
String type;
MyElement(String name, String type) {
this.name = name;
this.type = type;
}
}
public class Test {
public static void main(String[] args) {
Set<MyElement> set = new HashSet<MyElement>();
set.add(new MyElement("foo", "bar"));
set.add(new MyElement("foo", "bar"));
set.add(new MyElement("foo", "bar"));
System.out.println(set.size());
System.out.println(set.contains(new MyElement("foo", "bar")));
}
}
which when executed comes back with:
3
false
I would have expected the result to be 1 and true. Why are my elements not being recognised as being the same and how do I rectify this?
Thanks,
Wayne.
You need to implement
equals(Object o)andhashCode()on MyElement per the general contract. Absent thatSet.contains()will use the default implementation which compares the memory address of the objects. Since you’re creating a new instance of MyElement in the contains call it comes back as false.