集合的增加,删除

shirui8653719 2013-09-08 08:02:17
import java.util.HashSet;
import java.util.Set;

public class ShortSet {
public static void main(String[] args) {
// TODO Auto-generated method stub
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());
}
}

这道题的输出是什么?为什么,我判断错了。
...全文
226 10 打赏 收藏 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ceclinux 2013-09-09
  • 打赏
  • 举报
回复
被remove的对象要满足e要满足 (o==null ? e==null : o.equals(e)) equals比较两个对象你该懂的吧
  Short m=1;
        Integer t=1;
        System.out.println(m.equals(t));
ceclinux 2013-09-09
  • 打赏
  • 举报
回复
 System.out.println(s.remove(i-1));
if this set contains such an element. Returns true if this set contained the element (or equivalently, if this set changed as a result of the call). 可以这样测试下
wang171838 2013-09-09
  • 打赏
  • 举报
回复
我用的jdk是1.6.0_26运行后,发现这个程序没有问题的!
西电小楠 2013-09-08
  • 打赏
  • 举报
回复
好吧,长姿势了……
wind_elf 2013-09-08
  • 打赏
  • 举报
回复
试了一下,错误了。是remove(i-1)中的i-1时i变成int型的。可以加System.out.println(i.getClass()); 试一下。
wind_elf 2013-09-08
  • 打赏
  • 举报
回复
引用 3 楼 shirui8653719 的回复:
引用 1 楼 u011540494 的回复:
你把s.remove(i-1);改成remove((short)(i-1))试一下。
嗯,为什么删除的时候就变成int类型啦?
i++的时候i变成了int了,像2楼说的。
shirui8653719 2013-09-08
  • 打赏
  • 举报
回复
引用 1 楼 u011540494 的回复:
你把s.remove(i-1);改成remove((short)(i-1))试一下。
嗯,为什么删除的时候就变成int类型啦?
  • 打赏
  • 举报
回复
引用 1 楼 u011540494 的回复:
你把s.remove(i-1);改成remove((short)(i-1))试一下。
+1,,因为Java中的所有关于Short类型的计算,都会被自动转化为Integer类型,所以你remove(i - 1)意思就是去掉一个Integer类型的数据,但是Set中都是Short类型的,所以不能remove掉。当然了,前面你add的i,其实在循环时,i++,所以也被转成了Integer类型,但是泛型为Short,所以插入的时候,会再被自动转化为Short,所以可以插进去。
wind_elf 2013-09-08
  • 打赏
  • 举报
回复
你把s.remove(i-1);改成remove((short)(i-1))试一下。

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧