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?
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With