Java – what is the exact difference between these two sets of statements?

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

and

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

Solution

Suppose set S1 contains the same content in the first and second examples, and the final result should be the same

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

One advantage of using the HashSet (Collection) constructor is that its initial capacity is sufficient to accommodate the collection passed to the constructor (in this case, set S1):

However, when using the HashSet () constructor, the initial size is 16, so if through collection If the set added by addall is greater than 16, the size of the data structure must be adjusted:

Therefore, in terms of performance and efficiency, using the HashSet (Collection) constructor to create a HashSet may be a better choice

However, from the point of view of code readability, the variable name union seems to imply that the newly created set is the union of another set, so the code using the addall method may be easier to understand

If the idea is to create a new set from an existing set, the newly created set should be named with a different name, such as newset, copyofs1 or something similar

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>