0
Set<Integer> set = new HashSet<Integer>(); 
Integer i1 = 45; 
Integer i2 = 46; 
set.add(i1); 
set.add(i1); 
set.add(i2); System.out.print(set.size() + " "); 
set.remove(i2); System.out.print(set.size() + " "); 
i1 = 47; 
System.out.print(set.toString());
set.remove(i1); System.out.print(set.size() + " ");

The result of this code is 2,1,1 but my expectation is 2,1,0 Could any one help how does it works?
thanks in advance

Edited by anand01: n/a

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by anand01
1

I'm not sure what's the confusion here:

// add same elements twice; should be added only once
set.add(i1); 
set.add(i1);

// add new element; size is now 2
set.add(i2);

// remove added element, size is now 1
set.remove(i2);

// remove a non-existent element, shouldn't affect set
// size is still 1

// this part performs auto-boxing i.e. i1 now points to a new Integer object 
// having value 47
i1 = 47; 
set.remove(i1);

Edited by ~s.o.s~: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.