为什么不需要 Object.clone() 调用需要显式转换?这不是“向下转换总是需要和显式转换”规则的异常(exception)吗?我使用 javac 命令行和带有 JDK1.6.0_29 的 Eclipse Helios 编译并成功运行了以下代码。
public class Main {
public static void main(String[] args) {
byte[] original = { 1, 2, 3, 4 };
byte[] copy = original.clone();
for (byte b : copy) {
System.out.print(b + " ");
}
int[] originalInt = { 11, 22, 33, 44 };
int[] copyInt = originalInt.clone();
for (int i : copyInt) {
System.out.print(i + " ");
}
String[] originalStr = { "1", "2", "3", "4" };
String[] copyStr = originalStr.clone();
for (String s : copyStr) {
System.out.print(s + " ");
}
Main[] originalMain = { new Main() };
Main[] copyMain = originalMain.clone();
for (Main m : copyMain) {
System.out.print(m + " ");
}
} // end method main
} // end class Main
最佳答案
您没有调用 Object.clone()
。您正在调用 T[].clone()
,它被覆盖以返回 T[]
。
The members of an array type are all of the following:
- 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[]
.
关于java - Object.clone() 不应该需要显式转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703958/