Copying sets Java

后端 未结 5 997
清歌不尽
清歌不尽 2021-01-31 01:19

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

Set  itemList;
Set  tempList;

tempList = itemList;
<         


        
5条回答
  •  野性不改
    2021-01-31 01:28

    Another way to do this is to use the copy constructor:

    Collection oldSet = ...
    TreeSet newSet = new TreeSet(oldSet);
    

    Or create an empty set and add the elements:

    Collection oldSet = ...
    TreeSet newSet = new TreeSet();
    newSet.addAll(oldSet);
    

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


    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.

提交回复
热议问题