Array covariance and Arrays.copyOf

Ioi Lam ioi.lam at oracle.com
Fri Dec 14 06:56:01 UTC 2018


Arrays.copyOf is declared to return an Object[], but it will actually 
return a value array if its newType parameter is a value type. Javac 
will insert a checkcast if newType is known, so we're kind of OK:

     V[]doit(Object src[], int len, Class klass) {
returnArrays.copyOf(src, len, V.class);
     }
->
     5: invokestatic  #141    // 
java/util/Arrays.copyOf:([Ljava/lang/Object;ILjava/lang/Class;)[Ljava/lang/Object;
     8: checkcast     #48     // class "[V;"
    11: areturn


However, if newType is not known, the checkcast is not generated:

     Object[] doit(Object src[], int len, Class klass) {
         return Arrays.copyOf(src, len, klass);
     }

->
     5: invokestatic  #141    // 
java/util/Arrays.copyOf:([Ljava/lang/Object;ILjava/lang/Class;)[Ljava/lang/Object;
     8: areturn               // oops!


What's our plan for Arrays.copyOf?


Thanks
- Ioi



More information about the valhalla-dev mailing list