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 (i.e no i2 exists in the set), why is that?
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.P.S. The remove method of a set actually returns a boolean, so you can use
System.out.println(set.remove(i2))to see ifi2was really removed.