您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
xxhh 发布于2019年06月01日 14:34 最近更新于 2019年06月01日 14:45

这个程序为什么输出100?

2821 次浏览 读完需要≈ 1 分钟 Java
 public class ShortSet {
	public static void main(String args[]) {
		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());
	}
}

这个程序不应该输出1吗?因为for循环会把上一个元素删掉,但是为什么输出了100

1 个回答

一纸荒年 · 4年前

ishort类型,由于i-1运算时会自动提升表达式的类型;如果要删除,需要对应修改为:s.remove((short)(i - 1))

撰写答案