Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying sets Java

Tags:

java

copy

set

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

Set <Item> itemList; Set <Item> tempList;  tempList = itemList; 

or do you have to physically iterate through the sets and copy them one by one?

like image 260
SNpn Avatar asked Sep 24 '11 06:09

SNpn


People also ask

How do you copy elements from one set to another?

Use the clone() method to copy all elements from one set to another.

What does Copy () do in Java?

The copy() method of java. util. Collections class is used to copy all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list.


1 Answers

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

Collection<E> oldSet = ... TreeSet<E> newSet = new TreeSet<E>(oldSet); 

Or create an empty set and add the elements:

Collection<E> oldSet = ... TreeSet<E> newSet = new TreeSet<E>(); 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.

like image 89
Stephen C Avatar answered Oct 08 '22 15:10

Stephen C