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?