[英]Using the clone method without catching CloneNotSupportedException
I know that when using the clone method you're supposed to catch the CloneNotSupportedException. 我知道使用克隆方法时,您应该捕获CloneNotSupportedException。 However, I recently tried to clone an array of random integers just by invoking .clone( ) on the array, and it worked! 但是,我最近尝试仅通过在数组上调用.clone()来克隆随机整数数组,并且它起作用了! No try-catch block was necessary. 无需尝试捕获块。 The code was something like this: 代码是这样的:
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.
This code compiles and runs beautifully! 这段代码可以很好地编译和运行! But it does not require catching the CloneNotSupportedException inside a try-catch block. 但这并不需要在try-catch块中捕获CloneNotSupportedException。 Could someone please explain why this is the exception to the "rule" about catching that exception. 有人可以解释为什么这是关于捕获该异常的“规则”的异常。 Thank you!!! 谢谢!!!
The javadoc for Object.clone()
says: Object.clone()
的Javadoc说:
Note that all arrays are considered to implement the interface Cloneable 请注意,所有数组都被视为实现了Cloneable接口
Since the compiler knows that arrays are always cloneable, it knows that clone()
on an array will not raise CloneNotSupportedException
. 由于编译器知道数组始终是可clone()
,因此它知道数组上的clone()
不会引发CloneNotSupportedException
。 It doesn't make that assumption for other Cloneable
classes, but arrays as usual seem to be dealt with as a special case. 它没有对其他Cloneable
类做出这种假设,但是像往常一样,数组似乎是作为特殊情况处理的。
This is by definition. 这是根据定义。 The Java language specification says : Java语言规范说 :
10.7. 10.7。 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. 公共方法克隆,它覆盖类Object中相同名称的方法,并且不引发任何检查的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.