3

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?

1
  • 2
    You're not modifying the i2 that's in the set. You're modifying the reference i2; 46 will still be in the set. Commented Sep 2, 2012 at 14:01

3 Answers 3

6

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.

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 i2 was really removed.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.