有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查Set<E>是否已包含某些值

我有一个类,它存储整数对:

static class IntPair {
    int a;                  //JugsNode.a.content;
    int b;                  //JugsNode.b.content;

    public IntPair(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

以及一组定义如下:

static HashSet<IntPair> confs = new HashSet<IntPair>();

现在,它非常简单,我如何检查一个特定的IntPair p对象是否已经包含在这个集合中,而没有任何对它的引用,而只有它的值?更清楚地说:

IntPair p = new Pair(0, 0);
confs.add(p);

IntPair p1 = new Pair(0, 0);
confs.contains(p1); 

显然,最后一个调用返回false。那么,我如何通过只包含其值来检查该对是否被包含


共 (3) 个答案

  1. # 1 楼答案

    根据文件Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

    必须重写equalshashCode方法

  2. # 2 楼答案

    IntPair对象重写hashCode()equals()方法

    例如,你可以尝试以下方法

    @Overrid
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof IntPair)) return false;
    
        IntPair intPair = (IntPair) o;
    
        if (a != intPair.a) return false;
        if (b != intPair.b) return false;
    
        return true;
      }
    
    @Override
    public int hashCode() {
        int result = a;
        result = 31 * result + b;
        return result;
    }
    
  3. # 3 楼答案

    您需要重写equalshashCode

    static class IntPair {
        int a;           
        int b; 
    
       @Override
       public boolean equals(Object other){
         if(other==null) return false;
         if(!(other instanceof IntPair)) return false;
    
         IntPair o=(IntPair) other;
         return this.a==o.a && this.b==o.b;
       }
    
       @Override
       public int hashCode(){
         return 31*a+b;
       }
    }