RFR: 8289389: Fix warnings: type should also implement hashCode() since it overrides Object.equals() [v2]

Kevin Rushforth kcr at openjdk.org
Fri Jul 22 16:30:41 UTC 2022


On Tue, 19 Jul 2022 04:17:18 GMT, Nir Lisker <nlisker at openjdk.org> wrote:

>> you bring a good point, Kevin, thank you!
>
> I would use `Boolean.hashCode(relative);` for a `boolean`.
> 
> Kevin, I checked Effective Java 3rd Edition and it also says to use 0 (or some other constant) for `null`.

Using 0 for a null component of the hash is fine, as long as the accum variable is initialized to something > 0, and as long as you accumulate all values, even a 0. By which I mean that the following is not OK:


    int h = 1;
    if (comp1 != null) h = 31 * h + comp1.hashCode();
    if (comp2 != null) h = 31 * h + comp2.hashCode();


nor is this:


    int h = (comp1 == null) ? 0 : comp1.hashCode();
    h = 31 * h + (comp2 == null) ? 0 : comp2.hashCode();



but this is:


    int h = 1;
    h = 31 * h + (comp1 == null) ? 0 : comp1.hashCode();
    h = 31 * h + (comp2 == null) ? 0 : comp2.hashCode();


Anyway, the latest change in this PR is good.

-------------

PR: https://git.openjdk.org/jfx/pull/821


More information about the openjfx-dev mailing list