Copying sets Java

后端 未结 5 994
清歌不尽
清歌不尽 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:42

    The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

    findbugs says

    The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

    As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

    Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

    Set copy = new HashSet(map.size());
    for (Entry e : map.entrySet())
        copy.add(new java.util.AbstractMap.SimpleEntry(e));
    

    Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

提交回复
热议问题