s********e 发帖数: 340 | 1 3. import java.util.*;
4. public class Mapit {
5. public static void main(String[] args) {
6. Set set = new HashSet();
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. }
16. }
What is the result?
输出结果是 211
我不理解为什么是211呢?在第14行,set.remove(i2); 这个已经将i2从set中移除了,
我觉得 set这时应该是有0个元素,为什么显示set的size是1?
谢谢! |
h******3 发帖数: 351 | 2 Set does not allow duplicated items. Also, examine logically equal.
【在 s********e 的大作中提到】 : 3. import java.util.*; : 4. public class Mapit { : 5. public static void main(String[] args) { : 6. Set set = new HashSet(); : 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() + " ");
|
g**********y 发帖数: 14569 | 3 i2 = 47, set里是{46}, set.remove(i2) does nothing.
你把Eclipse的debugger打开,看一看就知道了。以后这种问题都可以问debugger. |
g*********g 发帖数: 114 | 4 2 1 1
because this hashset save the value rather than object.
And hashset do not save existed value in hashset.
So the line 11 . The hashset has two value.
So the line 12. Remove the value is 45. It exists in hashset . Thus it can
be removed. The size is 1
So the line 14. Remove the value is 47. It does not exist in hashset. Thus
nothing has been removed. The size also is 1. |
j**w 发帖数: 382 | 5
If you checked the return values from set.add() and set.remove, you would
know
【在 s********e 的大作中提到】 : 3. import java.util.*; : 4. public class Mapit { : 5. public static void main(String[] args) { : 6. Set set = new HashSet(); : 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() + " ");
|
x*****p 发帖数: 1707 | 6 2 1 1
Integer is immutable. So when i2=47, it becomes another integer and thus set
.remove(i2) can not remove the old i2=46. |