Can adding equals() and hashCode() method spoil something

Michu93 :

Is it possible that adding equals() and hashCode() methods will break already existing code?

I have a class with 3 fields, getters and setters:

public class Person {
private final String name;
private final List<Friend> friends;
private final Integer age;

to test this class I used: isEqualToComparingFieldByField() method to compare two Person objects instead of adding equals() and hashCode(). Other solution is to override equals() and hashCode() and use assertEquals() to compare these object but can I be totally sure that it won't break anything?

Jon Skeet :

Can I be totally sure that it won't break anything?

No. You're changing the meaning of equality from reference identity to a sort of value equality. You'll break anything relying on the current behaviour. For example, here's some valid code:

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();
}

Your proposed change would break that.

Do you actually have code like that? It's hard to tell.

More likely, if you want to change hashCode to include hashes from the List<Friend>, you could very easily break code unless the type is actually immutable. For example:

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));

Fundamentally, you need to be aware of what other code uses Person, so you know what it's relying on. If Person is immutable, that makes life much simpler because you don't need to worry about the second kind of problem. (Overriding equals() and hashCode() for mutable types is a fundamentally treacherous business.)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418337&siteId=1