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.
Example 1: Check the class of an object using getClass() In the above example, we have used the getClass() method of the Object class to get the class name of the objects obj1 and obj2 . To learn more, visit Java Object getClass().
The Java. util. Set. contains() method is used to check whether a specific element is present in the Set or not.
You need to implement equals(Object o)
and hashCode()
on MyElement per the general contract. Absent that Set.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.
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