简体   繁体   English

为什么这段代码打印100而不是1?

[英]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 anyone tell me why it prints 100 instead of 1? 谁能告诉我为什么打印100而不是1?

There seems to be some auto boxing going on...that is Java is automatically converting between Object and primitive... 似乎有一些自动装箱......那就是Java在Object和原语之间自动转换......

If I ... rename your class, use Short instead of short in the initialisation of the Set and then use... 如果我...重命名你的类,在Set的初始化中使用Short而不是short ,然后使用......

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());

It will print 100 ...but why? 它将打印100 ...但为什么?

To answer that, we need to take a closer look at the remove method... 要回答这个问题,我们需要仔细研究一下remove方法......

Set#remove(Object o) expects an Object , not the generic type like add , but an actual Object ...when you do i - 1 , Java assumes that 1 is an int and automatically scales the types up and auto boxes it as new Integer(i - 1) ...which clear does not exist within the set (you don't have any Integer objects!) Set#remove(Object o)需要一个Object ,而不是像add那样的泛型类型,而是一个实际的Object ...当你做i - 1 ,Java假设1是一个int并自动缩放类型并自动将其设置为new Integer(i - 1) ...在set中不存在clear(你没有任何Integer对象!)

However, if we change s.remove(i - 1); 但是,如果我们改变s.remove(i - 1); to s.remove((short)(i - 1)); s.remove((short)(i - 1)); , we force the conversion of the value back to short which then gets autoboxed as new Short(i - 1) , which does exist in your set and the end result is it will now print 1 ... ,我们强制将值转换回short ,然后将其作为new Short(i - 1)装箱,它确实存在于您的集合中,最终结果是它现在将打印1 ...

Simple ;) 简单;)

Upon running this code, I found that, after converting your primitive generic to java.lang.Short , the problem is when you do i-1 . 在运行此代码后,我发现在将原始泛型转换为java.lang.Short ,问题出在你执行i-1 short - int returns int , therefore the remove operation tries to remove an Integer from s . short - int返回int ,因此remove操作尝试从s删除Integer int and short , and, respectively, Integer and Short are very different. intshort ,以及IntegerShort分别非常不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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