[英]Java code using Set showing weird output?
The output of the following code should be 1 according to my logic. 根据我的逻辑,以下代码的输出应为1。 But its showing 100 instead. 但显示为100。 Can anyone explain me where is the problem? 谁能解释我的问题在哪里?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
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());
}
}
The result of 的结果
i-1
is of type int
. 是int
类型的。
This is described in the Java Language Specification, here . 这是在Java语言规范描述, 在这里 。
Binary numeric promotion is performed on the operands (§5.6.2). 对操作数执行二进制数值提升(第5.6.2节)。
This int
value then gets boxed to Integer
in order to be used as an argument to Set#remove(Object)
. 然后将此int
值装箱到Integer
以便用作Set#remove(Object)
。
The remove(Object)
method then uses this Integer
object to compare to the elements in the Set
, using Object#equals(Object)
. 然后, remove(Object)
方法使用此Integer
对象通过Object#equals(Object)
与Set
的元素进行比较。 But no Short
is equals
to an Integer
and no Integer
is equal
to a Short
. 但是没有Short
equals
Integer
,没有Integer
equal
Short
。 And therefore nothing gets removed. 因此,没有任何东西被删除。
The answer lays in out- and autoboxing: 答案在于装箱和自动装箱:
The statement i-1 is of type int
not of type Short
. 语句i-1的类型为int
而不是Short
类型。 The method remove()
accepts a parameter of type Object
(not necessarily the Generic type of the collection). 方法remove()
接受类型为Object
的参数(不一定是集合的Generic类型)。 Java will auto-box the numeric value as an Integer. Java会将数字值自动装箱为整数。 The Integer cannot be found in the set and will thus not be removed. 在集合中找不到整数,因此不会将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.