LinkedList:删除一个对象 [英] LinkedList: remove an object

查看:279
本文介绍了LinkedList:删除一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用for循环在Java中从LinkedList中查找和删除项目的有效方法,是否可能出现不一致:

Is this a valid way to find and remove item from a LinkedList in Java using a for each loop, is it possible that inconsistency may arise:

for(ObjectType ob : obList) {
  if(ob.getId() == id) {
    obList.remove(ob);
    break;
   }
}


推荐答案

其他已经提到了有效点,通常这不是你如何从集合中删除对象。但是,在这种情况下,一旦你删除打破就可以了。

Others have mentioned the valid point that normally this is not how you remove an object from a collection. HOWEVER, in this case it's fine since you break out of the loop once you remove.

但是,如果要在 remove 之后继续迭代,则需要使用迭代器。否则你将得到一个 ConcurrentModificationException ,或者在更一般的情况下,得到未定义的行为。

If you want to keep iterating after a remove, though, you need to use an iterator. Otherwise you'll get a ConcurrentModificationException, or in the more general case, undefined behavior.

所以是的,如果您删除之后中断 >,你会没事的

So yes, if you break out of the foreach after you remove, you'll be fine.

对于那些说这会失败的人,因为你可以'修改 foreach 中的集合 - 只有当你想继续迭代时才会这样。这不是这种情况,所以这个快捷方式很好。

To those who's saying that this will fail because you can't modify a collection in a foreach -- this is true only if you want to keep iterating. That's not the case here, so this shortcut is fine.

迭代器检查并抛出一个 ConcurrentModificationException 。这里,在 remove (符合并发修改条件)之后,你中断了。迭代器甚至没有机会检测它。

A ConcurrentModificationException is checked and thrown by the iterator. Here, after the remove (which qualifies as concurrent modification), you break out of the loop. The iterator doesn't even get a chance to detect it.

最好是在中断,为什么它是绝对必要的等等,因为如果稍后修改此代码以在 remove 之后继续迭代,它将失败

It may be best if you add a comment on the break, why it's absolutely necessary, etc, because if this code is later modified to continue iterating after a remove, it will fail.

我会把这个成语看作类似于 goto (或者更确切地说,标记为 break / 继续):一开始可能看起来不对,但是明智地使用它会使代码更清晰。

I would treat this idiom similar to goto (or rather, labeled break/continue): it may seem wrong at first, but when used wisely, it makes for a cleaner code.

这篇关于LinkedList:删除一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆