我知道在使用克隆方法时你应该捕获CloneNotSupportedException。但是,我最近试图通过在数组上调用.clone()来克隆一个随机整数数组,并且它有效!不需要try-catch块。代码是这样的:
import java.util.Arrays;
import java.util.Random;
public class ClonePractice
{
public static void main(String[ ] args)
{
int[ ] A = new int[100];
Random random = new Random( );
for( int i = 0; i < 100; i++ )
A[i] = 1 + random.nextInt(100); //Get random integer between 1 and 100.
int[ ] B = A.clone( );
B[0] = 1000;
System.out.println( Arrays.toString(A) );
System.out.println( Arrays.toString(B) );
// Arrays A and B should have different first values because they are
// independent objects in memory.
} // End of main method.
} // End of ClonePractice class.
此代码编译和运行精美!但它不需要在try-catch块中捕获CloneNotSupportedException。有人可以解释为什么这是&#34;规则&#34;的例外。关于抓住那个例外。谢谢!!!
答案 0 :(得分:0)
Object.clone()
的javadoc说:
请注意,所有数组都被视为实现Cloneable接口
由于编译器知道数组总是可克隆的,因此它知道数组上的clone()
不会引发CloneNotSupportedException
。它没有为其他Cloneable
类做出这种假设,但像往常一样的数组似乎是作为特例处理的。
答案 1 :(得分:0)
这是定义。 Java语言规范says:
10.7。数组成员
数组类型的成员全部如下:
...
公共方法clone,它覆盖Object类中的同名方法,并且不会抛出任何已检查的异常。