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.

最新文章

  1. PHP文件可限速下载代码
  2. C#拾遗-边边角角
  3. java 泛型编程学习
  4. String的length()和Array的length
  5. POJ 3276 Face The Right Way 反转
  6. LeetCode Number of Connected Components in an Undirected Graph
  7. Java控制语句——switch语句
  8. UITableViewCell之微博篇
  9. CODESOFT 2015中的条形码对象该如何创建
  10. webstore+nodejs
  11. 基于visual Studio2013解决面试题之0208二叉搜索树后序遍历序列
  12. 采用rest接口对接而非webservice
  13. Leetcode题解(七)
  14. 中文代码示例之Vuejs入门教程(一)
  15. [Leetcode]724. Find Pivot Index
  16. Visual Studio 2015 NuGet Update-Package 失败/报错:Update-Package : Unable to load the service index for source https://api.nuget.org/v3/index.json.
  17. RAID 0 ~ RAID 7
  18. [Object Tracking] Contour Detection through OpenCV
  19. ace后台管理系统扁平化框架
  20. SQL优化系列——子查询

热门文章

  1. ActiveMQ;RabbitMQ;ZeroMQ
  2. 【BZOJ-4456】旅行者 分治 + 最短路
  3. 【BZOJ-2893】征服王 最大费用最大流(带下界最小流)
  4. choop.php一句话脚本
  5. java重写equals方法
  6. 海边直播目标2017全国初中数学竞赛班课堂测试题解答-The Final
  7. JPA mysql wildfly jboss 存储时乱码
  8. js实现身份证号码验证
  9. VS快捷键大全(总结了一些记忆的口诀)
  10. 探究JavaScript中的五种事件处理程序