0

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?

Jai
  • 8,165
  • 2
  • 21
  • 52

2 Answers2

1

Properties don't override hashCode and equals. You can verify this by going to their documentation page (for example StringProperty) and scrolling down to where it says "Methods inherited from class java.lang.Object". If hashCode and equals are listed, then they aren't overridden.

Because of that, name.get().hashCode() would be correct, for example. name.hashCode() would return the identity hash code defined by Object.

The same can be said for equals. For example, name.equals(rhs.name) would call the base implementation from Object, which is the same as name == rhs.name.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
0

method hashCode() is to help computer know two objects is not equal quickly, two method you write above is ok. if you use java 1.7+, you can use

Objects.hash(filed1,filed2,filed3,.....)

to simplify.

刘思凡
  • 423
  • 2
  • 14