I am trying to add elements of pair in TreeSet, but somehow it is using the comparator to decide which value to be inserted.
class pair{
int i;
int j;
int w;
pair(int i,int j,int w){
this.i=i;
this.j=j;
this.w=w;
}
public boolean equals(Object o){
if(this==o) return true;
if(o==null || this.getClass()!=o.getClass()) return false;
pair p=(pair)o;
boolean a=i==p.i;
boolean b=j==p.j;
boolean c=w==p.w;
return (a && b && c);
}
public int hashCode(Object o){
return Objects.hash(i,j,w);
}
@Override
public String toString(){
return i + "-" + j + "-" + w;
}
}
public class CodeExample {
public static void main(String[] arg) {
TreeSet<pair> s = new TreeSet<>(new Comparator<>(){
public int compare(pair a , pair b){
return a.w-b.w;
}
});
pair p1 =new pair(1,3,3);
pair p2 =new pair(1,2,3);
pair p3 =new pair(2,2,3);
pair p4 =new pair(2,2,4);
if(p1.equals(p2))
System.out.println("P1 and P2 are equal");
s.add(p1);
s.add(p2);
s.add(p3);
s.add(p4);
System.out.println(s.size()); // OUTPUT = 2
while(!s.isEmpty()){
pair t = s.first();
System.out.println(t); //
s.remove(t);
}
}
}
Output
2
1-3-3
2-2-4
I am not sure why the p2 and p3 are not being inserted.
If I update the comparator to
TreeSet<pair> s = new TreeSet<>(new Comparator<>(){
public int compare(pair a , pair b){
if(a.w==b.w ){
if(a.i==b.i)
return a.j-b.j;
return a.i-b.i;
}
return a.w-b.w;
}
});
It is now adding all 4 elements. I thought comparator is only used while removing elements from the Set and the Set uses equals
and hashcode
to check if the Objects are duplicate, so why it is not inserting p2 and p3 (Same W value )in the first case?
I'm now sure why it is happening.