繁体   English   中英

将Integer对象添加到hashSet

[英]adding Integer objects to a hashSet

考虑以下代码:

6.  Set<Integer> set = new HashSet<Integer>();
7.  Integer i1 = 45;
8.  Integer i2 = 46;
9.  set.add(i1);
10. set.add(i1);
11. set.add(i2); System.out.print(set.size() + " ");
12. set.remove(i1); System.out.print(set.size() + " ");
13. i2 = 47;
14. set.remove(i2); System.out.print(set.size() + " ");
15. System.out.println(set.contains(i2));

代码输出:

2 1 1 false

在第14行之后,我假定大小为0但为1 我猜想在第13行将新对象i2添加到集合中,所以我在第15行进行了测试,但它返回false (即集合中不存在i2 ),为什么呢?

您实际上从不会从第14行的集合中删除任何内容,因为您将前一行的i2重新分配给集合中没有的其他内容。 尝试查看一下,当您完全删除第13行时会发生什么。

PS集合的remove方法实际上返回一个布尔值,因此您可以使用System.out.println(set.remove(i2))来查看是否真正删除了i2

[45,46] -> Remove 45 > [46] -> Remove 47 > [46]由于不存在47。 同样,当您为i2分配自动装箱引用时,该引用也会更改,但哈希集仍包含旧值。

1. Set维护其中数据唯一性

所以添加了所有数据后的set

[46, 45]

看到这条痕迹...

[46,45]

set.remove(i1)

[46]

i2 = 47;
set.remove(i2);

[46] // as i2 = 47, but you didn't add it to the set

所以现在i2 = 47 不在集合中,所以它为假。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM