Sunday, February 22, 2009

Be careful with collection operations

Set set = new SomeSet();
short i=7;
set.add(i);
set.remove(i-1+1);
System.out.println("Size = " + set.size());

It prints 1 not 0.

Note i is short variable.
set.add(i) -> you are inserting short Object (auto boxing enters the picture).
set.remove(i-1+1) -> Here - operation promotes i to int and returns the result as int.
Finally we are trying to remove integer object (auto unboxing enters the picture).

Hence the answer is 1.

No comments: