views:

192

answers:

4
Set<Type> union = new HashSet<Type>(s1);

And

Set<Type> union = new HashSet<Type>();
Set<Type> s1 = new HashSet<Type>();
union.addAll(s1);
+1  A: 

There is no difference. Both will create a new set that contains all of the elements in the set s1.

Of course, your second code sample won't even compile, since you can't directly instantiate the Set interface, but I'm assuming that you meant to say new HashSet instead of new Set.

Eli Courtwright
+5  A: 

Assuming that Set s1 contains the same contents in the first and second examples, the end results should come out to be the same.

(However, the second example will not compile because a Set is an interface rather than a concrete class.)

One advantage of using the HashSet(Collection) constructor is that it will have an initial capacity that is enough to hold the Collection (in this case, the Set s1) that is passed into the constructor:

Constructs a new set containing the elements in the specified collection. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to contain the elements in the specified collection.

However, using the HashSet() constructor, the initial size is 16, so if the Set that was added via the Collection.addAll is larger than 16, there would have to be a resizing of the data structure:

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

Therefore, using the HashSet(Collection) constructor to create the HashSet would probably be a better option in terms of performance and efficiency.

However, from the standpoint of readability of the code, the variable name union seems to imply that the newly created Set is an union of another Set, so probably the one using the addAll method would be more understandable code.

If the idea is just to make a new Set from an existing one, then the newly created Set should probably be named differently, such as newSet, copyOfS1 or something to that effect.

coobird
Well said .
jjnguy
+7  A: 

The first will be more efficient because the second Set will be created with the correct amount of space in the backing data structure where in the second piece of code, the Set will have to resize to make room for the new elements.

As far as end results go, they are the same.

jjnguy
+1  A: 

There is a little difference, in that the new HashSet(s1) will make sure beforehand that all elements will fit, and no rehashing is needed.

Roel Spilker