gpt4 book ai didi

java - 重写 equals 方法时违反自反性规则

转载 作者:搜寻专家 更新时间:2023-11-01 01:23:29 24 4
gpt4 key购买 nike

我对 Effective Java 这本书有疑问。疑问是关于 equals 方法
反身规则违反。书中是这样说的:

"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."

为了测试它我写了一个示例类,但是 contains 方法不返回 false 它返回 true。谁能告诉我问题出在哪里?

最佳答案

我同意这个程序的结果是 indeed puzzling :

import java.util.*;

class Item {
@Override
public boolean equals(Object obj) {
return false; // not even equal to itself.
}
}

class Test {
public static void main(String[] args) {
Collection<Item> items = new HashSet<Item>();
Item i = new Item();
items.add(i);
System.out.println(items.contains(i)); // Prints true!
}
}

答案是 contains实现检查 argument == object在做之前 argument.equals(object) .结果来自 containstrueitem == item持有,即使item.equals(item)返回 false。

假设equals follows its contract(自反),这种实现方式 contains是正确的。


如果您仔细阅读您发布的引用,作者包含了“几乎”这个词 :) 看起来您偶然发现了该规则的少数异常(exception)之一。


其他集合(例如 ArrayList)使用 equals直接,如果你从 new HashSet<Item>() 改变至 new ArrayList<Item>()在上面的程序中它 prints false 正如预期的那样。

关于java - 重写 equals 方法时违反自反性规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909401/

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