Why does this code print 100 instead of 1?

public class Short {
    public static void main(String[] args) {

        Set s = new HashSet();

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

        System.out.print(s.size());
    }

}

Can someone tell me why it prints 100 instead of 1?

+4
source share
2 answers

It seems that some kind of automatic boxing is happening ... that is, Java is automatically converted between Objectand primitive ...

If I ... rename your class, use Shortinstead Shortin initialization Set, and then use ...

Set<Short> s = new HashSet<Short>();

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

System.out.println(s.size());

He will print 100... but why?

To answer this question, we need to study the method more carefully remove...

Set#remove(Object o) Object, add, Object... i - 1, Java , 1 int new Integer(i - 1)... Set ( Integer!)

, s.remove(i - 1); s.remove((short)(i - 1));, Short, new Short(i - 1), , 1...

;)

+10

, java.lang.Short , i-1. short - int int, remove Integer s. int short, Integer short .

+2

All Articles