[records] updates for Preview 9. hashCode

John Rose john.r.rose at oracle.com
Tue Jan 14 00:07:16 UTC 2020

On Jan 13, 2020, at 3:47 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> Overall this is good -- though I am not quite sure what the last bit means here, about "derived from the behavior of Object::equals"?  
>  122      * The precise algorithm used in the implicitly provided implementation
>  123      * is unspecified and is subject to change,
>  124      * within the limits of the contract of {@code Object.hashCode}
>  125      * as derived from the behavior of {@code Object.equals}.

The contract of Object::hashCode refers to the behavior of Object::equals,
and not much else.  That’s what I mean by one contract being derived
from the behavior of another.  There’s probably a better way to say it…?

The important things are that (a) Record::equals refines the contract of
Object::equals by mandating component-wise comparison (and nothing
else), at least in the default implementation.  And (b) Record::hashCode
must be compatible with Record::equals, deriving a combined hash from
the values of the components.  I didn’t say *hashCodes* of the components,
just *hashes*, because recursively using the honest actual *hashCodes* of
the components needlessly constrains the implicit implementation.

In the case of primitives, and probably also in the case of other types
like nested records, if you are given a record (or tree of records), you can
sometimes find faster ways to hash than first hashing every single field
(and subtree, if you are doing a tree).  For example, in a record of four
bytes, you could pick them all up at once into a 32-bit word, and then
do a little mixing.  For typical records, there might be an advantage
to dividing the work (on primitives and other “easy” stuff) into 64-bit
words or even hardware vectors larger than 64 bits.  We buy an
option on such future optimizations simply by refusing to give TMI
about the implicit hashCode implementation, not even the seemingly
harmless assurance that it recursively calls hashCode on wrappers.

— John

P.S. In all of this I haven’t said how *bad* the wrapper hashCode
methods are.  Oops, there I said it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20200113/ebdd9532/attachment.htm>

More information about the amber-spec-experts mailing list