It is common knowledge that when equals()
is overridden, hashCode()
must also be overridden.
This is a typical example of this in a non-JavaFX bean class.
public class Person {
private String name;
private int age;
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return Objects.equals(name, rhs.name) &&
age == rhs.age;
}
}
The JavaFX bean:
public class Person {
private StringProperty name;
private IntegerProperty age;
// Option A
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age.hashCode();
return result;
}
// Option B
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.get().hashCode();
result = 31 * result + age.get().hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return Objects.equals(name.get(), rhs.name.get()) &&
Objects.equals(age.get(), rhs.age.get());
}
}
So which of the 2 methods is the correct way to write hashCode()
? Or is the correct method something totally different?