这两组报表之间有什么确切的区别? [英] What is the exact difference between these two groups of statements?
问题描述
Set<Type> union = new HashSet<Type>(s1);
和
Set<Type> union = new HashSet<Type>();
Set<Type> s1 = new HashSet<Type>();
union.addAll(s1);
推荐答案
假设 code>
s1
在第一个和第二个例子中包含相同的内容,最终结果应该是一样的。
Assuming that Set
s1
contains the same contents in the first and second examples, the end results should come out to be the same.
(但是,第二个例子不会编译,因为 Set
是一个接口而不是一个具体类。)
(However, the second example will not compile because a Set
is an interface rather than a concrete class.)
使用 HashSet(Collection)
构造函数的初始容量足以容纳集合
(在这种情况下,传递到构造函数中的 Set
s1
):
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:
构造一个包含指定集合中的
元素的新集合。
HashMap
创建时默认使用
负载因子(0.75)和初始
容量来容纳
元素
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.
但是,使用 HashSet()
构造函数,初始大小为16 ,因此如果通过 Set AbstractCollection.html#addAll(java.util.Collection)rel =nofollow noreferrer> Collection.addAll
大于16,则必须调整数据结构大小:
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:
构造一个新的空集;
backHashMap
实例默认
初始容量(16)和负载因子
(0.75)。
Constructs a new, empty set; the backing
HashMap
instance has default initial capacity (16) and load factor (0.75).
因此,使用 HashSet(Collection)
构造函数创建 HashSet
在性能和效率方面可能是更好的选择。
Therefore, using the HashSet(Collection)
constructor to create the HashSet
would probably be a better option in terms of performance and efficiency.
但是,从代码的可读性的角度来看,变量名 union
似乎意味着新创建的 Set
是另一个 Set
,所以可能使用 addAll
方法的代码是更容易理解的代码。
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.
从现有的设置
设置 c>,然后新创建的
, Set
应该命名不同, code> newSet copyOfS1
或其他效果。
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.
这篇关于这两组报表之间有什么确切的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!