问题描述
有没有办法复制一个treeset?也就是可以去吗
is there a way to copy a treeset? that is, is it possible to go
set- itemlist; set
- templist; templist = itemlist;
或者您是否必须对集合进行物理迭代并逐个复制它们?
or do you have to physically iterate through the sets and copy them one by one?
推荐答案
另一种方法是使用 复制构造函数:
collectionoldset = ... treeset newset = new treeset (oldset);
或者创建一个空集并添加元素:
or create an empty set and add the elements:
collectionoldset = ... treeset newset = new treeset (); 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.