Search code examples
javaarraysclone

Why can clone array without type cast?


Found that I can do following:

package test.java.lang;
import java.util.Arrays;

    public class Tester_ArrayCloning_01 {

        public static void main(String[] args) {
            double[] vals1 = {1.2, 2.3, 3.4, 4.5};
            double[] vals2;

            // vals2 = (double[])vals1.clone(); // was thinking should do so
            vals2 = vals1.clone(); // but happened can do so

            System.out.println(Arrays.toString(vals2));
        }

    }

Why? When it was introduced?


Solution

  • From section 10.7 of the JLS, array members:

    The members of an array type are all of the following:

    ...

    • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    The same section in the third edition has the same content.

    The second edition says that array types override clone(), but at that point there was no return type covariance, so they couldn't have done so returning T[].

    So basically it was introduced in 1.5.