0

I'm trying to use HashSet in java 8 with an overridden .equals() method. Here's a example of the code I'm using:

import java.util.HashSet;

public class Test{
    String id;
    int a;

    public Test (String i, int a){
            this.id = i;
            this.a = a;
    }

    @Override
    public boolean equals(Object obj){
        if (obj instanceof Test){
            if (((Test)obj).id == this.id){
                    return true;
            }

        }
        return false;
    }



    public static void main(String[] args){
        HashSet<Test> set = new HashSet<Test>();

        Test a = new Test("hello", 1);
        Test b = new Test("hello", 2);

        System.out.println("equals?\t\t" + a.equals(b));

        set.add(a);

        System.out.println("contains b?\t" + set.contains(b));
        System.out.println("contains a?\t" + set.contains(a));

        System.out.println("specific?\t" + (b == null ? a == null : b.equals(a)));

    }

}

Here's the output:

equals?         true
contains b?     false
contains a?     true
specific?       true

As you can see, .equals() passes as expected, but contains() does not behave as I would expect.

According to the documentation, contains() should pass "if and only if this set contains an element e such that (o==null ? e==null : o.equals(e))". I ran that exact code and it passes, so why does contains() still fail?

ewok
  • 20,148
  • 51
  • 149
  • 254
  • 1
    The contains logic is being inherited from the Collections type. Hashset uses the hashcode to determine uniqueness. – lordoku Jan 20 '16 at 18:51
  • then why does the documentation say it uses equals? – ewok Jan 20 '16 at 18:53
  • 1
    http://stackoverflow.com/questions/7026564/understanding-contains-method-of-java-hashset – lordoku Jan 20 '16 at 18:53
  • 2
    Also the underlying container for HashSet is HashMap. The objects are stored as keys within the HashMap. The contains method calls the contains key, which uses the hashcode to find the index of the map and then uses the equals of the object. If the hashcode isn't matching, then it won't find the index. – lordoku Jan 20 '16 at 18:55
  • 1
    You override equals() but not hashCode() in Test. This leads to trouble when used as keys in hash-based collections, which is exactly the trouble you're having now. – Brian Goetz Jan 20 '16 at 23:44

0 Answers0