java arraylist 拷贝数据,如何将一个ArrayList的内容复制到另一个?

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

ArrayList myObject = new ArrayList();

ArrayList myTempObject = new ArrayList();

//fill myTempObject here

....

//make myObject contain the same values as myTempObject

myObject = myTempObject;

//free up memory by clearing myTempObject

myTempObject.clear();

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.

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

解决方案

You can use such trick:

myObject = new ArrayList(myTempObject);

or use

myObject = (ArrayList)myTempObject.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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值