由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 急问一个Java Hashset的 考试题。
相关主题
请教一下subset I 输出子集顺序问题上道图论的吧
面试题求解:remove first duplicate number from an arrayjava 求助
FB电面fail很讨厌做greedy的题
Facebook Hacker Cup有些面试题是够扯蛋的
subset求个4sum的算法
leetcode的3sum的运行时间问题问个递归的问题
3sum on LeetCode OJLeetCode 的 4 sum 问题 如何用hash table做呢?
combination sum II请问如何去除结果里面的重复
相关话题的讨论汇总
话题: i2话题: hashset话题: integer话题: set话题: i1
进入JobHunting版参与讨论
1 (共1页)
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.
1 (共1页)
进入JobHunting版参与讨论
相关主题
请问如何去除结果里面的重复subset
一道面试题和解法(求指点).leetcode的3sum的运行时间问题
ebay is a joke3sum on LeetCode OJ
4sum o(n^2)超时combination sum II
请教一下subset I 输出子集顺序问题上道图论的吧
面试题求解:remove first duplicate number from an arrayjava 求助
FB电面fail很讨厌做greedy的题
Facebook Hacker Cup有些面试题是够扯蛋的
相关话题的讨论汇总
话题: i2话题: hashset话题: integer话题: set话题: i1