复制集Java [英] Copying sets Java

查看:67
本文介绍了复制集Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以复制 TreeSet ?也就是说,是否可以

Is there a way to copy a TreeSet? That is, is it possible to go

Set <Item> itemList;
Set <Item> tempList;

tempList = itemList;

还是您必须物理遍历集合并逐个复制它们?

or do you have to physically iterate through the sets and copy them one by one?

推荐答案

另一种方法是使用复制构造函数

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);

或创建一个空集并添加元素:

Or create an empty set and add the elements:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);

clone 不同,这些允许您使用不同的集合类,不同的比较器,甚至填充其他(非集合)集合类型。

Unlike clone these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.

请注意,复制 Set 的结果是一个新的 Set ,其中包含对作为原始元素的对象的引用设置。元素对象本身不会被复制或克隆。这符合Java Collection API设计为起作用的方式:它们不复制元素对象。

Note that the result of copying a Set is a new Set containing references to the objects that are elements if the original Set. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection APIs are designed to work: they don't copy the element objects.

这篇关于复制集Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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