如何克隆ArrayList并克隆其内容? [英] How to clone ArrayList and also clone its contents?

查看:408
本文介绍了如何克隆ArrayList并克隆其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何克隆 ArrayList 并且还可以在Java中克隆它的项目?

How can I clone an ArrayList and also clone its items in Java?

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....

clonedList 与狗列表中的不一样。

And I would expect that objects in clonedList are not the same as in dogs list.

推荐答案

public static List<Dog> cloneList(List<Dog> list) {
    List<Dog> clone = new ArrayList<Dog>(list.size());
    for (Dog item : list) clone.add(item.clone());
    return clone;
}



为了工作,显然,你必须得到你的Dog对象实现Cloneable接口和clone()方法。

For that to work, obviously, you will have to get your Dog object to implement the Cloneable interface, and the clone() method.

这篇关于如何克隆ArrayList并克隆其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆