Eslam Hamdy
Eslam Hamdy

Reputation: 7386

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 (i.e no i2 exists in the set), why is that?

Upvotes: 3

Views: 20026

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

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.

Upvotes: 2

Amit Deshpande
Amit Deshpande

Reputation: 19185

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

Upvotes: 2

arshajii
arshajii

Reputation: 129507

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.

Upvotes: 6

Related Questions