Before someone asks, I've already read through the responses under this similar posting (.Contains() method not calling Overridden equals method) and was still unable to fix my issue;
I created a custom object called Tuple
. Here it is:
class Tuple implements Comparable<Tuple> {
public int x = -1;
public int y = -1;
public int val = -1;
public Tuple(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
@Override
public boolean equals(Object o) {
if (o instanceof Tuple) {
Tuple o2 = (Tuple) o;
if(this.x == o2.x && this.y == o2.y) {
return true;
}
}
return false;
}
@Override
public int compareTo(Tuple t) {
if(this.val < t.val) {
return -1;
} else if(this.val > t.val) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return "(" + x + "," + y + "," + val + ")";
}
}
I created a HashSet
and added objects to it, checking for equality:
HashSet<Tuple> set = new HashSet<Tuple>();
Tuple t1 = new Tuple(2, 1, 10);
Tuple t2 = new Tuple(2, 1, 10);
test1.add(t1);
System.out.println(test1.contains(t1));
System.out.println(test1.contains(t2));
System.out.println(t1.equals(t2));
System.out.println(t2.equals(t1));
System.out.println(t1.equals(t1));
System.out.println(t2.equals(t2));
This is the output:
true
false
true
true
true
true
I am expecting test1.contains(t2)
to produce true
since t1
and t2
are equal. As you can see, I made sure to check both reflexivity and symmetry for equals
.