Java Programming Test Question 3

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.

 

转载于:https://www.cnblogs.com/fuzhihong0917/p/5703678.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值