Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can clone array without type cast?

Tags:

java

arrays

clone

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?

like image 587
Suzan Cioc Avatar asked Dec 07 '22 08:12

Suzan Cioc


2 Answers

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.

like image 124
Jon Skeet Avatar answered Dec 22 '22 01:12

Jon Skeet


The return type of the method clone for an array of type T[] is T[]. Since Object.clone() return Object such definition requires covariant return types, that were introduced in Java 5.

Previously, clone was defined to return Object. That is particularly the kind of issues for what covariant return types are good for,

like image 21
Javier Avatar answered Dec 21 '22 23:12

Javier