Java HashSet remove(e) method doesn't behave as I expected

I am unable to understand the logic behind it.

Case 1:

HashSet shortSet = new HashSet();
    for (short i = 0; i < 3; i++) {
        shortSet.add(i);
        shortSet.remove(i - 1);
    }
    System.out.println(shortSet.size() + "    shortSet : " + shortSet);

Op :Size : 3 shortSet : [0, 1, 2]

Case 2 :

HashSet shortSet = new HashSet();
    for (int i = 0; i < 3; i++) {
        shortSet.add(i);
        shortSet.remove(i - 1);
    }
    System.out.println("Size : "+shortSet.size() + "    shortSet : " + shortSet);

Op : Size : 1 shortSet : [2]

I just want to understand the main reason behind this, why these two output are different Just By changing from short to int . what happens behind the scene.

Jon Skeet
people
quotationmark

The problem is that in the first case, the expression i is of type short, whereas the expression i - 1 is of type int. Those values are being boxed to Short and Integer respectively - the Integer isn't in the set, so can't be removed.

You can fix this with a cast:

for (short i = 0; i < 3; i++) {
    shortSet.add(i);
    shortSet.remove((short) (i - 1));
}

In your second case, both i and i - 1 are of type int (then boxed to Integer), so the entries you're adding can also be removed...

people

See more on this question at Stackoverflow