调用在Java中的foreach循环中删除 [英] Calling remove in foreach loop in Java

查看:294
本文介绍了调用在Java中的foreach循环中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,使用foreach循环迭代集合时调用集合上的remove是否合法?例如:

  List< String> names = .... 
(String name:names){
//做某事
names.remove(name)。





$ p

作为附录,删除尚未迭代的项目是否合法然而?例如,

  //假设名称列表为重复条目
List< String> (String name:names){
//做某事
while(names.remove(name));


解决方案

例如:

 <$ c $在迭代它的时候,你应该使用一个Iterator。

C>列表与LT;字符串> names = ....
Iterator< String>我= names.iterator();
while(i.hasNext()){
String s = i.next(); //必须先调用i.remove()
//做某事
i.remove();


p>这个类的迭代器和listIterator
方法返回的迭代器是快速失败的:如果在创建迭代器后的任何
时间结构上修改列表,除了通过
迭代器自己的删除或添加方法,迭代器将抛出
ConcurrentModificationException。因此,面对并发的
修改,迭代器会快速而干净地失败,而不是在
将来在未定的时间
冒着任意的,非确定性的行为。


也许很多新手不清楚的是,使用for / foreach构造迭代列表隐式地创建了一个必须不可访问的迭代器。这些信息可以在这里找到


In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:

List<String> names = ....
for (String name : names) {
   // Do something
   names.remove(name).
}

As an addendum, is it legal to remove items that have not been iterated over yet? For instance,

//Assume that the names list as duplicate entries
List<String> names = ....
for (String name : names) {
    // Do something
    while (names.remove(name));
}

解决方案

To safely remove from a collection while iterating over it you should use an Iterator.

For example:

List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}

From the Java Documentation :

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here

这篇关于调用在Java中的foreach循环中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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