import java.util.HashSet; public class JPTQuestion3 { public static void main(String[] args) { HashSet shortSet = new HashSet(); for (short i = 0; i < 100; i++) { shortSet.add(i); shortSet.remove(i - 1); } System.out.println(shortSet.size()); } }
输出:100。
如果把循环变量改为int型的, 那么
import java.util.HashSet; public class JPTQuestion3 { public static void main(String[] args) { HashSet shortSet = new HashSet(); for (int i = 0; i < 100; i++) { shortSet.add(i); shortSet.remove(i-1); } System.out.println(shortSet.size()); } }
输出:1
这是什么坑啊。而且,这HashSet竟然不指定泛型就在用了-_-
为什么范围比int小的的就不会被移除,而大于等于int范围的就会被移除?泛型指定与否都与结果无关。
原因:.........................................i-1是int型的,HashSet里面存的是Short类型的,所以,没有一个数字被移除。
官方解释:自动装箱的作用
Java Programming Test Question 3 Answer and Explanation
The size of the shortSet will be 100. Java Autoboxing feature has been introduced in JDK 5, so while adding the short to HashSet<Short> it will automatically convert it to Short object. Now i-1 will be converted to int while evaluation and after that it will autoboxed to Integer object but there are no Integer object in the HashSet, so it will not remove anything from the HashSet and finally its size will be 100.