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

Recommended Answers

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 …
Jump to Post

All 2 Replies

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);

thanks for your replay ~s.o.s~..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.