【发布时间】:2016-03-22 20:39:02
【问题描述】:
我知道在使用克隆方法时,您应该捕获 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。有人可以解释为什么这是关于捕获该异常的“规则”的例外。谢谢!!!
【问题讨论】:
-
编译器知道数组总是可克隆的,因此数组上的
clone()不会引发CloneNotSupportedException。 -
“当使用克隆方法时你应该捕获 CloneNotSupportedException”是什么让你产生了这个想法?