Copying sets Java(复制集 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
,其中包含对作为元素的对象的引用,如果原始 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:复制集 Java


基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01