对对象覆盖等于,以便反向对也相同
Pair object overriding equals so that reverse pairs are also the same
我想定义一对 class,其中 <2,3> 和 <3,2> 是同一事物。 equal 方法被覆盖,但我不确定如何覆盖 hashcode 函数以匹配它。到目前为止我的代码是:
Set<Pair> edgePairs=new HashSet<>();
edgePairs.add(new Pair(2,3));
edgePairs.add(new Pair(2,4));
edgePairs.add(new Pair(2,5));
edgePairs.add(new Pair(4,2));
edgePairs.add(new Pair(2,3));
edgePairs.add(new Pair(3,2));
for (Pair edgePair : edgePairs) {
System.out.println(edgePair.x+" "+edgePair.y);
}
输出:
2 3
2 4
2 5
4 2
3 2
正确的输出不应包含对 <4,2> 和 <3,2>
一对Class:
public class Pair
{
int x, y;
public Pair(int x, int y) {
this.x = x; this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair that = (Pair) o;
if ((x == that.y && y == that.x)||(x == that.x && y == that.y))
return true;
return false;
}
@Override
public int hashCode() {
int result = x; result = 31 * result + y;
return result;
}
}
如果您只是让 hashCode
return x + y
,而不将它们中的任何一个乘以 31,那么参数的顺序无关紧要。
你真的很接近,你只需要使散列函数更具体
@Override
public int hashCode() {
int a = 0, b = 0;
if (x > y) {
a = x;
b = y
} else {
a = y;
b = x;
}
int result = a; result = 31 * result + b;
return result;
}
或者您可以重做 Pair
class 并按升序存储 x 和 y。
无论哪种方式,您都需要将哈希方程中变量的顺序与输入变量的顺序分开。
我想定义一对 class,其中 <2,3> 和 <3,2> 是同一事物。 equal 方法被覆盖,但我不确定如何覆盖 hashcode 函数以匹配它。到目前为止我的代码是:
Set<Pair> edgePairs=new HashSet<>();
edgePairs.add(new Pair(2,3));
edgePairs.add(new Pair(2,4));
edgePairs.add(new Pair(2,5));
edgePairs.add(new Pair(4,2));
edgePairs.add(new Pair(2,3));
edgePairs.add(new Pair(3,2));
for (Pair edgePair : edgePairs) {
System.out.println(edgePair.x+" "+edgePair.y);
}
输出:
2 3
2 4
2 5
4 2
3 2
正确的输出不应包含对 <4,2> 和 <3,2>
一对Class:
public class Pair
{
int x, y;
public Pair(int x, int y) {
this.x = x; this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair that = (Pair) o;
if ((x == that.y && y == that.x)||(x == that.x && y == that.y))
return true;
return false;
}
@Override
public int hashCode() {
int result = x; result = 31 * result + y;
return result;
}
}
如果您只是让 hashCode
return x + y
,而不将它们中的任何一个乘以 31,那么参数的顺序无关紧要。
你真的很接近,你只需要使散列函数更具体
@Override
public int hashCode() {
int a = 0, b = 0;
if (x > y) {
a = x;
b = y
} else {
a = y;
b = x;
}
int result = a; result = 31 * result + b;
return result;
}
或者您可以重做 Pair
class 并按升序存储 x 和 y。
无论哪种方式,您都需要将哈希方程中变量的顺序与输入变量的顺序分开。