[英]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: 和一个Set定义如下:
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? 现在,这非常简单,如何检查特定的IntPair p
对象是否已包含在此集中,而没有引用它的值,而仅引用了它的值? 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
. 显然,此最后一次调用返回false
。 So, how can I check that that pair is contained by having only its values. 因此,如何通过仅具有其值来检查该对是否包含。
You need to override equals
and hashCode
. 您需要覆盖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;
}
}
Override hashCode()
and equals()
method for IntPair
objects. 覆盖IntPair
对象的hashCode()
和equals()
方法。
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)).
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 您必须重写equals
和hashCode
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.