What is the exact difference between these two groups of statements?

collections, java

Solution

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.

Problem

``` Set<Type> union = new HashSet<Type>(s1); ``` And ``` Set<Type> union = new HashSet<Type>(); Set<Type> s1 = new HashSet<Type>(); union.addAll(s1); ```

Original source