java 将 Integer 对象添加到 hashSet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12236490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:08:01  来源:igfitidea点击:

adding Integer objects to a hashSet

javasethashset

提问by Java Player

Consider the following code:

考虑以下代码:

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));

The code outputs:

代码输出:

2 1 1 false

2 1 1 false

After line 14 I assumed that the size would be 0but it is 1. I guess that a new object i2is added to the set at line 13, so I tested that at line 15 but it returns false(i.e no i2exists in the set), why is that?

在第 14 行之后,我假设大小01. 我猜i2在第 13 行将一个新对象添加到集合中,所以我在第 15 行测试了它,但它返回false(即i2集合中不存在),这是为什么?

回答by arshajii

You never actually remove anything from the set on line 14 because you reassign i2on the previous line to something different that is not in the set. Try seeing what happens when you remove line 13 altogether.

您实际上从未从第 14 行的集合中删除任何内容,因为您i2在前一行重新分配了不在集合中的不同内容。试着看看当你完全删除第 13 行时会发生什么。

P.S. The remove method of a set actually returns a boolean, so you can use System.out.println(set.remove(i2))to see if i2was really removed.

PS set 的remove 方法实际上返回的是一个布尔值,所以你可以用它System.out.println(set.remove(i2))来查看是否i2真的被移除了。

回答by Amit Deshpande

[45,46]-> Remove 45->[46]->Remove 47-> [46]As 47 is not present. Also when you assign i2 with autoboxing reference is changed but hashset still contains old value.

[45,46]-> Remove 45-> [46]-> Remove 47->[46]因为 47 不存在。此外,当您使用自动装箱引用分配 i2 时,但 hashset 仍包含旧值。

回答by Kumar Vivek Mitra

1.A Set maintains the UNIQUENESS of datain it.

1.Set 维护其中数据UNIQUENESS

So the setafter addition of all the data in it was

所以set在添加所有数据之后是

[46, 45]

See this trace...

看到这个痕迹...

[46,45]

set.remove(i1)

[46]

[46]

i2 = 47;
set.remove(i2);

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

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

so now as i2 = 47its not in the set, so its false.

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