What is the difference between these two groups of utterances?

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

and

Set<Type> union = new HashSet<Type>();
Set<Type> s1 = new HashSet<Type>();
union.addAll(s1);
+3
source share
4 answers

Assuming it Set s1contains the same content in the first and second examples, the final results should match.

(However, the second example will not compile because it Setis an interface, not a specific class.)

One of the advantages of using a constructor HashSet(Collection)is that it will have an initial capacity sufficient for storage Collection(in this case Set s1), which is passed to the constructor:

, . HashMap (0,75) .

, HashSet(), 16, , Set, Collection.addAll 16, :

; backing HashMap (16) (0,75).

, HashSet(Collection) HashSet, , .

, , union, -, , Set Set, , , , addAll, .

, Set , , , Set -, newSet, copyOfS1 - .

+5

, Set , Set , .

, .

+7

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

Of course, your second code sample will not even compile, since you cannot directly create an interface Set, but I assume that you wanted to say new HashSetinstead new Set.

+1
source

There is a slight difference in the fact that the new HashSet (s1) will pre-check that all elements will match and no re-writing is required.

+1
source

Source: https://habr.com/ru/post/1711485/


All Articles