集合关心唯一性,因此在程序中实现集合时,我们必须重写java.lang.Object
equals()
和hashCode()
方法,这样我们就不会出现重复的情况。引用在 JVM 的单个当前实例的上下文中保持其有效性,记住这一点,我尝试以这种方式编码我的程序。在 TestSet.main
中(第 4-6 行)。我尝试通过在这些行中使用注释来以实用的方式提出我的查询。
class TestCase {
transient private int x;
private int y;
public TestCase(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (o instanceof TestCase && (((TestCase) o).getXValue() == getYValue()))
return true;
else
return false;
}
public int hashCode() {
return x + y;
}
public int getXValue() {
return x;
}
public int getYValue() {
return y;
}
}
class TestSet {
public static void main(String[] args) {
TestCase tc1 = new TestCase(4, 8);
TestCase tc2 = new TestCase(4, 8);
Set<TestCase> set = new HashSet<TestCase>();
set.add(tc1);//succeeds
set.add(tc2);//succeeds
System.out.println(set.add(tc2));//fails and gives us false.
tc2 = new TestCase(4, 8);
System.out.println(set.add(tc2));//succeeds and gives us true?
System.out.println(set.size());
System.out.println(set.contains(tc1));
System.out.println(set.contains(tc2));
}
}
最佳答案
您的 equals 方法中有一个拼写错误:您正在将一个元素的 x
与另一个元素的 y
进行比较。这几乎没有任何意义;您应该比较 x 和 y。
您应该将等于
实现为
return o instanceof TestCase
&& ((TestCase) o).getXValue() == getXValue()
&& ((TestCase) o).getYValue() == getYValue();
第二个 .add(tc2)
返回 false
的原因是 HashSet
的实现使用 ==
检查作为一种优化,并且恰好捕获了该特定情况。这不会改变 .equals
方法的缺陷。
关于java - 对象的哈希码是否有任何内部映射到我们在类中重写的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058409/