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
。那么,我如何通过只包含其值来检查该对是否被包含
# 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)).
必须重写
equals
和hashCode
方法# 2 楼答案
为
IntPair
对象重写hashCode()
和equals()
方法例如,你可以尝试以下方法
# 3 楼答案
您需要重写
equals
和hashCode