我看过其他时候在 StackOverflow 上问过这个问题,但其他用例似乎都没有解决我的问题。HashSet 似乎没有意识到两个对象是相同的。
基本上,这是我的课。
private static class Inconsistency
{
int a;
int b;
boolean isConsistency;
//Default constructor. To be used when we don't have an inconsistency
public Inconsistency()
{
this.a = -1;
this.b = -1;
this.isConsistency = false;
}
public Inconsistency(int a, int b, boolean isConsistency)
{
this.a = a;
this.b = b;
this.isConsistency = isConsistency;
}
@Override
public String toString()
{
if (this.isConsistency)
{
return "(" + this.a + ", " + this.b + ")";
}
else
{
return "No inconsistency";
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + a;
result = prime * result + b;
result = prime * result + (isConsistency ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object other)
{
if (this == other)
{
return true;
}
if (other == null)
{
return false;
}
我正在尝试将我的类的对象存储在哈希图中。
使用我定义 equals 方法的方式,不一致 A (10, 20, true) 应该等于另一个不一致 B (20, 10, true),当我测试我的 equals 方法时,它可以正常工作。但是,当我尝试将 A 和 B 都插入 HashSet 时,它们都被错误地添加了。我知道我应该操纵我的哈希码函数,但我不知道该怎么做。
MMTTMM
相关分类