clone()
方法默认在 Object
类中不可见,那么它如何不对数组类型给出错误?
这是否意味着有一个名为 int[] 的类型,其实现是用 java 编写的,如果是,在哪里可以找到它?
既然已经写了,为什么不完整地写出来呢?
我的意思是为什么不正确实现每个方法而不仅仅是 Object
类的行为。
int[] a ={1,2,3};
Object object = new Object();
object.clone();//Does not compile since clone is protected.
a.clone();// allowed as this method is from int[]
最佳答案
所有数组都实现 Cloneable 接口(interface)。
请参阅 Java 语言规范的相关部分:§10.7 Array Members
The public method
clone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
. A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
关于java - 为什么数组允许使用克隆方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12086115/