Complicated
Complicated

Reputation: 85

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.

Upvotes: 3

Views: 709

Answers (2)

Jakub H
Jakub H

Reputation: 2158

In the first example you are trying to remove Integer, because i-1 expression is promoted to Integer. In your HashSet you have only Shorts so that's the reason why it doesn't remove anything.

Btw since Java 1.5 you shouldn't use raw type of any collections.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500445

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

Upvotes: 8

Related Questions