考虑下面的代码:
ArrayList<Double> list1 = new ArrayList<>();
list1.add(1.5);
list1.add(2.5);
list1.add(3.5);
ArrayList<Double> list2 = (ArrayList<Double>)list1.clone();
Date[] list3 = {new Date(), new Date(4664316)};
Date[] list4 = list3.clone();
int[] list5 = {1, 2};
int[] list6 = list5.clone();
为什么list.clone()需要转换,而list3.clone()和list5.clone()不需要转换?我知道 array 和 ArrayList 之间的区别,但不确定具体原因。
最佳答案
请阅读documentation .
Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type.
但是在ArrayList中,返回的是一个Object,因此需要进行强制转换。
关于java - 什么时候需要使用clone()方法进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28957337/