List remove object的问题

fanlyfly_jim 2010-01-22 03:53:28
optRightAllList里有5个对象,都可以打印出来,但程序当加了remove操作后,只打印前四个对象了,本来根据条件能remove两个对象的,现在漏掉remove最后一个对象,究竟是什么原因?
Iterator<SysOptRight> iter = optRightAllList.iterator();
while(iter.hasNext()){
SysOptRight sysOptRight = iter.next();
System.out.println("***********" +sysOptRight.getSourceid());
for(SysOptRight sysUserOptRight:optUserReadRightList){
if(sysOptRight.getSourceid().equals(sysUserOptRight.getSourceid())){
optRightAllList.remove(sysOptRight);
}
}
}

...全文
432 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
琢磨
fanlyfly_jim 2010-01-22
  • 打赏
  • 举报
回复
解决了 按照4楼的方法 结贴
yangsan83 2010-01-22
  • 打赏
  • 举报
回复
楼上什么意思
SambaGao 2010-01-22
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 amdgaming 的回复:]
不要在 迭代的 时候 删除 元素 会 报 异常的,老大,你这样是不对的
[/Quote]

..
不吃鱼的熊 2010-01-22
  • 打赏
  • 举报
回复
[Quote=引用楼主 fanlyfly_jim 的回复:]
optRightAllList里有5个对象,都可以打印出来,但程序当加了remove操作后,只打印前四个对象了,本来根据条件能remove两个对象的,现在漏掉remove最后一个对象,究竟是什么原因?
Iterator <SysOptRight> iter = optRightAllList.iterator();
while(iter.hasNext()){
SysOptRight sysOptRight = iter.next();
System.out.println("***********" +sysOptRight.getSourceid());
for(SysOptRight sysUserOptRight:optUserReadRightList){
if(sysOptRight.getSourceid().equals(sysUserOptRight.getSourceid())){
optRightAllList.remove(sysOptRight);
}
}
}
[/Quote]
不要在迭代的时候删除元素,可以考虑遍历你需要删除的元素集合,在其中删除!
奔跑哥 2010-01-22
  • 打赏
  • 举报
回复
在使用迭代器的时候,不要remove,这样迭代器会失效,故会产生不正确的结果。
fanlyfly_jim 2010-01-22
  • 打赏
  • 举报
回复
SysOptRight类没有equals()和hashCode()方法,需要再生成吗
bayougeng 2010-01-22
  • 打赏
  • 举报
回复
你可再做一个List。
把要删的元素都放在里面。
循环结束以后再optUserReadRightList.removeAll(list);
我也觉得你的hashCode方法和equals方法有问题。
Johnson_Hong 2010-01-22
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 amdgaming 的回复:]
不要在 迭代的 时候 删除 元素 会 报 异常的,老大,你这样是不对的
[/Quote]

是的

用for(int i=c.size()-1;i>=0;i--){
remove(c.get(i));
}

另外,如果改成上面的写法还是不对,请检查equals方法,equals方法改写的不对也会导致你说的问题
amdgaming 2010-01-22
  • 打赏
  • 举报
回复
不要在 迭代的 时候 删除 元素 会 报 异常的,老大,你这样是不对的
Dan1980 2010-01-22
  • 打赏
  • 举报
回复
可能你的SysOptRight类的equals()和hashCode()方法有问题。

62,614

社区成员

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

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