The copy constructor given by @Stephen C is the way you created Set (or when you know where it came from). When this comes from Map.entrySet() , it will depend on the Map implementation you use:
findbugs says
The entrySet () method allows you to return a Map view in which one Entry is reused and returned during iteration. Starting with Java 1.6, both IdentityHashMap and EnumMap have done this. When repeating using such a Map, the Entry value is valid only until you proceed to the next iteration. If, for example, you try to pass such an entrySet method for the addAll method, everything will be bad.
Since addAll() is called by the copy constructor, you can find yourself with a set of only one record: the last.
Not all Map implementations do this, so if you know that your implementation is safe in this regard, the copy constructor is definitely the way to go. Otherwise, you will have to create new Entry objects yourself:
Set<K,V> copy = new HashSet<K,V>(map.size()); for (Entry<K,V> e : map.entrySet()) copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));
Edit: Unlike the tests I ran on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment no longer fits. This may have been the case in earlier versions of Java 6 (before u45), but I don't need to test.
Matthieu Sep 18 '15 at 15:49 2015-09-18 15:49
source share