【问题标题】:Checking if Set<E> already contains some values检查 Set<E> 是否已经包含一些值
【发布时间】:2013-12-19 17:18:41
【问题描述】:

我有这个存储成对 int 的类:

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。那么,我如何通过仅包含其值来检查该对是否包含在内。

【问题讨论】:

  • 顺便说一句。使您的a 和b 字段final。

标签: java set contains


【解决方案1】:

您需要覆盖equals 和hashCode。

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

【讨论】:

    【解决方案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】:

      根据文档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)).

      您必须覆盖 equals 和 hashCode 方法

      【讨论】:

        猜你喜欢
        • 2011-04-09
        • 1970-01-01
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 2012-05-13
        相关资源
        最近更新 更多