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

查看:86
本文介绍了如何将一个 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.

如何使用 java 在 myObject 中保留 myTempObject 的值?

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

但您应该记住,所有这些方式都会为您提供列表的副本,而不是其中的所有元素.因此,如果您更改复制的 List 中的元素之一,它也会在您的原始 List 中更改.

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天全站免登陆