gpt4 book ai didi

java - Collection 的 contains 方法是否会为添加到其中的实例返回 false?

转载 作者:行者123 更新时间:2023-12-02 07:21:24 26 4
gpt4 key购买 nike

我正在阅读 Joshua Bloch 的在线章节“重写 equals() 方法”。这是link 。以下部分让我感到困惑,

Reflexivity—The first requirement says merely that an object must be equal to itself. It is hard to imagine violating this requirement unintentionally. If you were to violate it and then add an instance of your class to a collection, the collection’s contains method would almost certainly say that the collection did not contain the instance that you just added.

问题 - 集合的包含方法是否有可能在添加到集合的实例上返回 false?

我尝试过,但返回的结果始终为 true。

最佳答案

为了说明这一点,有一个简单的类:

class C {
private int i;
public C(int i) { this.i = i; }
}

现在,如果你这样做:

C c1 = new C(1);
C c2 = new C(1);

List<C> l = new ArrayList<C>();

l.add(c1);

l.contains(c2) 将返回 false,因为 c2.equals(c1)false ,尽管两个实例具有相同的构造函数参数。

这是因为类 C 不会覆盖 .equals().hashCode()

一般来说,每次您的类必然要在任何类型的Collection 中使用时,您最好重写这两个方法。在这种情况下:

// Note: final class, final member -- that makes this class immutable
final class C {
private final int i;
public C(int i) { this.i = i; }

@Override
public int hashCode() { return i; }
@Override
public boolean equals(Object o)
{
// no object equals null
if (o == null)
return false;
// an object is always equal to itself
if (this == o)
return true;
// immutable class: if the class of the other is not the same,
// objects are not equal
if (getClass() != o.getClass())
return false;
// Both objects are of the same class: check their members
return i == ((C) o).i;
}
}

关于java - Collection 的 contains 方法是否会为添加到其中的实例返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14173742/

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