如何将一个ArrayList的内容复制到另一个? [英] How do I copy the contents of one ArrayList into another?

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

问题描述

我有一些数据结构,我想使用一个作为临时数据,另一个不是临时数据。

I have some data structures, and I would like to use one as a temporary, and another as not temporary.

ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();


//fill myTempObject here
....

//make myObject contain the same values as myTempObject
myObject = myTempObject;

//free up memory by clearing myTempObject
myTempObject.clear();

现在问题当然是 myObject 实际上只是指向 myTempObject ,因此一旦 myTempObject 被清除,那么 myObject

now the problem with this of course is that myObject is really just pointing to myTempObject, and so once myTempObject is cleared, so is myObject.

如何在<$ c $中保留 myTempObject 中的值c> myObject 使用java?

How do I retain the values from myTempObject in myObject using java?

推荐答案

你可以使用这样的技巧:

You can use such trick:

myObject = new ArrayList<Object>(myTempObject);

或使用

myObject = (ArrayList<Object>)myTempObject.clone();

您可以获得有关clone()方法的一些信息这里

You can get some information about clone() method here

但是你应该记住,所有这些方法都会为你提供列表的副本,而不是它的所有元素。因此,如果您更改复制列表中的某个元素,它也会在原始列表中更改。

But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.

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

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