添加 equals()
和 hashCode()
方法是否可能会破坏现有代码?
我有一个包含 3 个字段、getter 和 setter 的类:
public class Person {
private final String name;
private final List<Friend> friends;
private final Integer age;
为了测试这个类,我使用了:isEqualToComparingFieldByField()
方法来比较两个 Person
对象,而不是添加 equals()
和 哈希码()
。其他解决方案是覆盖 equals()
和 hashCode()
并使用 assertEquals()
来比较这些对象,但我可以完全确定它不会破坏任何东西吗?
最佳答案
Can I be totally sure that it won't break anything?
没有。您正在将相等的含义从引用标识更改为某种值相等。你会破坏任何依赖于当前行为的东西。例如,这里有一些有效的代码:
Person person1 = new Person("Foo", 100);
Person person2 = new Person("Foo", 100);
// This is fine. Two distinct Person objects will never be equal...
if (person1.equals(person2)) {
launchNuclearMissiles();
}
您提议的更改会破坏它。
你真的有这样的代码吗?很难说。
更有可能,如果你想改变hashCode
包括来自 List<Friend>
的哈希值,除非类型实际上是不可变的,否则您可以很容易地破坏代码。例如:
Map<Person, String> map = new HashMap<>();
Person person = new Person("Foo", 100);
map.put(person, "Some value");
// If this changes the result of hashCode()...
person.addFriend(new Friend("Bar"));
// ... then you may not be able to find even the same object in the map.
System.out.println(map.get(person));
从根本上说,您需要了解其他代码使用了什么 Person
,所以你知道它依赖什么。如果Person
是不可变的,这让生活变得简单多,因为你不需要担心第二种问题。 (为可变类型覆盖 equals()
和 hashCode()
从根本上说是危险的事情。)
关于java - 添加 equals() 和 hashCode() 方法会破坏某些东西吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60323094/