在 java 中使用 Tree Set 和用户定义的类

问题描述 投票:0回答:0

我试图在 TreeSet 中添加 pair 的元素,但不知何故它正在使用比较器来决定要插入的值。

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);
         }
    }
}

输出

2 
1-3-3
2-2-4

我不确定为什么没有插入 p2 和 p3。

如果我将比较器更新为

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;
     }
});

现在添加所有 4 个元素。我认为比较器仅在从 Set 中删除元素时使用,而 Set 使用

equals
hashcode
来检查对象是否重复,那么为什么在第一种情况下不插入 p2 和 p3(相同的 W 值)?

我现在知道为什么会这样了。

java set comparator priority-queue treeset
© www.soinside.com 2019 - 2024. All rights reserved.