java - 什么时候需要使用clone()方法进行转换?

标签 java clone

考虑下面的代码:

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/

相关文章:

c++ - 如何克隆子类而不重复代码?

javascript - 将另一个元素内容替换为悬停元素内容

java - HttpSessionListener 是否一直有效?

java - 为什么我的 UI 在浏览器中运行与在我的计算机 (Java Swing) 上运行时会丢失格式?

java - 对于 OOP,是否应该尽可能频繁地将方法转换为对象?

jQuery:克隆一个div并将其插入到具有顺序id的最后一个div之后

javascript - 获取页面上每个元素的 Z-index

javascript - 将 HTML 从原始文档复制到弹出窗口(使用 JQuery)

java - 类、对象、引用变量在 Java 中存储在哪里。在堆中还是在堆栈中?堆或堆栈位于何处?

java - 如何在 Java Swing 中命名坐标(点)