如何复制 List<Integer> 的值,而不是引用进入另一个列表? [英] How to copy values, not references, of List&lt;Integer&gt; into another list?

查看:47
本文介绍了如何复制 List<Integer> 的值,而不是引用进入另一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也就是说,在不引用同一个对象的情况下,我需要将一个列表的元素值复制到另一个列表中.这些是列表:

Namely, without referencing the same object, I need to copy values of elements of one list into another list. These are the lists:

List<Integer> listA = new ArrayList<Integer>();
List<Integer> ListB = new ArrayList<Integer>();

listA = (added some values);

listB = (do what?)...

附注.我为初学者的问题道歉,但我从来没有做过这样的事情.

PS. I appologize for beginner's question, but I have never done such a thing.

推荐答案

你可以试试看一下Collections.copy 方法:

You can try and give a look at the Collections.copy method:

public static void copy(List dest,列表源代码)

public static void copy(List dest, List src)

将一个列表中的所有元素复制到另一个列表中.操作后,每次复制的索引目标列表中的元素将与其在目标列表中的索引相同来源清单.目标列表必须至少与来源清单.如果它更长,则剩余的元素目的地列表不受影响.该方法在线性时间内运行.

Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. This method runs in linear time.

参数: dest - 目的地列表.src - 源列表.

Parameters: dest - The destination list. src - The source list.

注意:以上应该适用于简单的数据类型,例如整数,但是,如果您有自己的对象,而这些对象又可能会引用其他对象,则您必须遍历每个对象并分别复制.

Note: The above should work for simple data types such as Integers, however, if you have your own objects which might in turn reference other objects, you will have to iterate over each object and copy it separately.

这篇关于如何复制 List<Integer> 的值,而不是引用进入另一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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