简体   繁体   中英

Checking if Set<E> already contains some values

I have this class which stores pairs of 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;
    }
}

and a Set defined as follow:

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

Now, it's quite simple, how can I check if a particular IntPair p object is already contained in this set without having any reference to its but only its values? More clearly:

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

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

Obviously this last call returns false . So, how can I check that that pair is contained by having only its values.

You need to override equals and 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;
   }
}

Override hashCode() and equals() method for IntPair objects.

For example you can try as follows

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

Per documentation 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)). 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)).

You have to override equals and hashCode methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM