Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do define my own element class for use with Set

Tags:

java

set

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.

like image 445
Wayne Avatar asked Mar 11 '11 22:03

Wayne


People also ask

How do you know what class an object belongs to?

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().

Is element in set Java?

The Java. util. Set. contains() method is used to check whether a specific element is present in the Set or not.


1 Answers

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.

like image 157
Jeremy Avatar answered Sep 23 '22 01:09

Jeremy