加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 这两组语句之间的确切区别是什么?

发布时间:2020-12-15 05:15:27 所属栏目:Java 来源:网络整理
导读:SetType union = new HashSetType(s1); 和 SetType union = new HashSetType();SetType s1 = new HashSetType();union.addAll(s1); 解决方法 假设Set s1在第一个和第二个例子中包含相同的内容,最终结果应该是相同的. (但是,第二个示例不会编译,因为Set是一个
Set<Type> union = new HashSet<Type>(s1);

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

解决方法

假设Set s1在第一个和第二个例子中包含相同的内容,最终结果应该是相同的.

(但是,第二个示例不会编译,因为Set是一个接口而不是具体的类.)

使用HashSet(Collection)构造函数的一个优点是它的初始容量足以容纳传递给构造函数的Collection(在本例中为Set s1):

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,因此如果通过Collection.addAll添加的Set大于16,则必须调整数据结构的大小:

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

因此,在性能和效率方面,使用HashSet(Collection)构造函数创建HashSet可能是更好的选择.

但是,从代码的可读性的角度来看,变量名称union似乎暗示新创建的Set是另一个Set的并集,因此使用addAll方法的那个可能是更容易理解的代码.

如果想法只是从现有的Set创建一个新的Set,那么新创建的Set应该以不同的名称命名,例如newSet,copyOfS1或其他类似的东西.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读