# How to make a copy of a set

• 06-11-2009, 11:54 PM
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, 12: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>();

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>();
//originalSet.removeAll(toRemove);
System.out.println(originalSet);

// now restore
originalSet = copyOfSet;
System.out.println(originalSet);
}
}

• 06-12-2009, 12: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.

Thanks for your help :-)
• 06-12-2009, 07:45 AM
pbrockway2
Both the new HashSet(Collection) and new ArrayList(Collection) give you a reference to a new collection containing the given elements (hence the "new") and certainly not a reference to an existing set or list.

Using a "getter" method won't change this. (Assuming you "get" the set before you make changes to its contents.)

One thing to remember is that the things referenced by the contents of the original set are not copied. So if you add and remove elements from the set you can get the original contents back again by using the copy. But if you change the state of the set elements then those changes that will affect the state of the copy elements (because the elements of the set and the copy reference the same objects.) This isn't a problem with Integer, but it may show up if you have a set of mutable things.

The commented bit of the code I posted should prove to you that the copy is proof against changes made with removeAll(). And addAll() is similar.