# How to make a copy of a set

• 06-12-2009, 12:54 AM
ZebV43
How to make a copy of a set
When working with destructive bulk operations on a set I know that I have to make a copy if I don't want to change the original set. I do not know how to make this copy though. I used this code in a recent exam but it was wrong can anyone explain why and what I should be doing?

Code:

`Set<Integer> copyOfSet = new HashSet<Integer>(originalSet);`
• 06-12-2009, 01:17 AM
pbrockway2
You may have to explain what "wrong" means, and possible what "destructive bulk operations" are.

The following works for me (that is, the set contents are altered and then restored:

Code:

```import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class CopySet {     public static void main(String[] args) {         Set<Integer> originalSet = new HashSet<Integer>();         originalSet.add(-1);         originalSet.add(42);         originalSet.add(666);                         Set<Integer> copyOfSet = new HashSet<Integer>(originalSet);                             // "destructive" operation on the original set         Iterator<Integer> it = originalSet.iterator();         while(it.hasNext()) {             if(it.next() == 42) {                 it.remove();             }         }         //Set<Integer> toRemove = new HashSet<Integer>();         //toRemove.add(42);         //originalSet.removeAll(toRemove);         System.out.println(originalSet);                             // now restore         originalSet = copyOfSet;         System.out.println(originalSet);     } }```
• 06-12-2009, 01:46 AM
ZebV43
Hi, thanks for replying so quickly.

By wrong I was told that I was just creating another reference to the existing Set rather than creating a new object.

The destructive bulk operations I meant were (set.addAll set.retainAll set.removeAll).

In the actual exam I used a getter method to add the originalSet to the TreeSet constructor. Maybe this is what I did wrong?

Code:

`Set<Integer> copyOfSet = new ArrayList<Integer>(this.getOriginalSet());`
But If the code in my original post works for you then I think I may have to assume that I did something else silly in the exam! As long as I have the right idea now I guess that is the important thing.