gpt4 book ai didi

java - 以下情况的 hashCode() 方法 : two sets are equal when they have at least one element in common?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:04:54 24 4
gpt4 key购买 nike

我目前面临这样一种情况,我有字符串元组(大小为 2),如果两个元组至少有一个共同元素,则它们应该被视为相等。我有以下类实现这个想法:

public class MyTuple
{
private List<String> list = Arrays.asList(new String[2]);

public List<String> getList()
{
return list;
}

public void set(String firstElement, String secondElement)
{
list.set(0, firstElement);
list.set(1, secondElement);
}

@Override
public boolean equals(Object other)
{
if (other instanceof MyTuple) {
return !Collections.disjoint(this.list, ((MyTuple) other).getList());
}
return false;
}
}

但是,根据 hashCode() 约定:

If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.

如何覆盖我的 hashCode() 方法而不违反契约?

最佳答案

在考虑hashCode()之前,我认为你应该首先重新考虑你对equals()的设计。我认为您无法实现 equals() 并履行所需的契约(Contract)——尤其是关于传递性

的契约(Contract)

发件人:Java Doc of Object#equals()

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.

  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

  • For any non-null reference value x, x.equals(null) should return false.

为什么?我可以构造您的 MyTuple 的三个对象:

  • A = {x1, x2}
  • B = {x2, x3}
  • C = {x3, x4}

其中 x1x2x3x4 都是不同的。现在我有

  • A.equals(B) 返回真
  • B.equals(C) 返回真
  • C.equals(A) 返回 false

而且他们违反了传递性契约。

我认为你应该考虑使用你自己的另一个关系(也许是 partialEquals())这样你就不必遵守契约。但是之后您也不能使用equals() 之类的方法并期望MyTuple 起作用,例如,HashMapHashSet

关于java - 以下情况的 hashCode() 方法 : two sets are equal when they have at least one element in common?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41861065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com