简体   繁体   中英

adding Integer objects to a hashSet

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

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

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

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

[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.

1. A Set maintains the UNIQUENESS of data in it.

So the set after addition of all the data in it was

[46, 45]

See this trace...

[46,45]

set.remove(i1)

[46]

i2 = 47;
set.remove(i2);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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