Using switch patterns to rewrite Arrays.deepHashCode

Brian Goetz brian.goetz at oracle.com
Sat Sep 11 13:48:05 UTC 2021


Thanks Tagir, this is a helpful exploration.  There are lots of places 
in the JDK (and the world beyond) that assume "eight primitive types, no 
more"; finding them is a game of whack-a-mole.  The real question is how 
many of them would fall back to something reasonable when the ninth 
primitive shows up, vs how many would blow up.

THe good news is that, because primitives extend Object, code that says 
"do X for primitives, otherwise fall back to Object::hashCode (or 
::toString or whatever) is likely to usually work.

A synthetic "array" supertype is something we've discussed a few times, 
but always got distracted before coming to any conclusions.

> final int elementHash = switch(element) {
>    case null -> 0;
>    case AnyArray anyArray -> switch(anyArray) {
>      case Object[] arr -> deepHashCode(arr);
>      case byte[] arr   -> hashCode(arr);
>      case short[] arr  -> hashCode(arr);
>      case char[] arr   -> hashCode(arr);
>      case int[] arr    -> hashCode(arr);
>      case long[] arr   -> hashCode(arr);
>      case float[] arr  -> hashCode(arr);
>      case double[] arr -> hashCode(arr);
>      // no default case!
>    };
>    default -> element.hashCode();
> };

You would need to reorder this switch!  Because byte[] will be a subtype 
of Object[].


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20210911/890b0743/attachment.htm>


More information about the amber-spec-experts mailing list