简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM