Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniqueness in sets

Tags:

java

If I take for example a HashSet<E>, and add objects to it, how does it check if the object's already there?

I have the following simple setup:

private class MyObject {
    String text;

    public MyObject(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object o) {
        if (o != null && o instanceof MyObject) {
            return ((MyObject) o).text.equals(text);
        }

        return false;
    }

}

In my project I have many objects like this, but all initialized separately. I want to filter the doubles, by adding all to a Set, like this:

MyObject m1 = new MyObject("1");
MyObject m2 = new MyObject("1");
MyObject m3 = new MyObject("2");

System.out.println(m1.equals(m2)); //expected: true, result: true
System.out.println(m1.equals(m3)); //expected: false, result: false

Set<MyObject> myObjects = new HashSet<MyObject>();
myObjects.add(m1);
myObjects.add(m2);
myObjects.add(m3);

System.out.println(myObjects.size()); //expected: 2, result: 3

Set<String> stringList = new HashSet<String>();
stringList.add("1");
stringList.add("1");
stringList.add("2");
System.out.println(stringList.size()); //expected: 2, result: 2

How can I make it so that my myObjects set does not contain these doubles? So m1 and m2 are different instances, but have the same content so I only need m1.

Edit
Based on Mathias Schwarz's answer I've implemented the hashCode() function as follows:

@Override
        public int hashCode() {
            return text.hashCode();
        }

But how would I implement this method if I have a more complex class with multiple fields?

like image 493
nhaarman Avatar asked Aug 02 '26 21:08

nhaarman


2 Answers

HashSet determines whether two object are identical on the results of invoking equals and hashCode on the object. You must implement hashCode if you implement equals. If they are inconsistent, HashSet will not behave correctly... So the important thing is how those two methods are implemented on MyObject (which btw is really a class...).

like image 114
Mathias Schwarz Avatar answered Aug 04 '26 11:08

Mathias Schwarz


If your using eclipse then Right Click --> Source --> Generate hashCode and Equals .If you what to know more about hash code and equals read this portion from Effective Java .

like image 33
Emil Avatar answered Aug 04 '26 10:08

Emil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!