TreeSet implements Set inteface, and thus prevents duplicate insertion. I used to think that when a new item is added to a set, its hashcode is computed, and afterwards the new item is being compared, using Object.equals()
, to every other existing item, which might has the same hashcode as the new item. If a match is found, the new item will not be added eventually.
However, according to this, the following code is suppose to produce the output 3. That's because two Point variables are considered 'equal' if and only if they refer to the same address in the memory. While running this code shows that the actual output is 2, which means equality of two object is defined by compareTo
instead of equals
.
Can you explain this behavior?
public class Point implements Comparable<Point> {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point other) {
return Integer.compare(other.y, this.y);
}
@Override
public boolean equals(Object other) {
return this == other;
}
public static void main(String[] args){
Set<Point> mySet = new TreeSet<>();
mySet.add(new Point(1,2));
mySet.add(new Point(2,2));
mySet.add(new Point(3,1));
System.out.println(mySet.size());
}
}
Edit: According to TreeSet documentation:
the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface