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