简体   繁体   English

Java迭代器和for-each-loop。 任何方式访问底层迭代器?

[英]Java iterators and for-each-loop. any way to access the underlying iterator?

I very much like the for-each-loop construction ( for(T e : iterable) ) in Java which works on any Iterable<T> because it makes in many cases very easy to read and to write code. 我非常喜欢Java中的for-each-loop构造( for(T e : iterable) ),它适用于任何Iterable<T>因为它在很多情况下非常容易阅读和编写代码。

I wonder though if there is any way that I can access the underlying iterator from such a loop. 我想知道是否有任何方法可以从这样的循环访问底层迭代器。 This can be mandatory if I want to use the remove() from the iterator. 如果我想使用迭代器中的remove() ,这可能是必需的。

No, the whole point of the for-each-loop is to abstract away the underlying iterator. 不,for-each-loop的重点是抽象掉底层迭代器。

If you need it, you must declare it. 如果需要,您必须申报。

No, you cannot remove objects in a for each loop. 不,您无法删除每个循环中的对象。

Use this instead: 请改用:

Iterator<Type> it = collection.iterator();

while (it.hasNext()) {
   if (it.next().shouldBeRemoved()) {
       it.remove();
   }
}

请改用for循环。

If the collection is reasonably small, you can alternatively use a copy of the collection to iterate if you want to be able to remove elements so you won't have to act as if you have two collections. 如果集合相当小,您可以使用集合的副本进行迭代,如果您希望能够删除元素,那么您就不必像使用两个集合那样进行操作。

for(T e : collection.clone())
    if(e.shouldBeRemoved())
        collection.remove();

Even better, Apache CollectionUtils (and there is probably a Google alternative and a generics alternative) provides filter(java.util.Collection collection, Predicate predicate) . 更好的是,Apache CollectionUtils(可能还有Google替代品和泛型替代品)提供filter(java.util.Collection collection, Predicate predicate) This example returns the whole list. 此示例返回整个列表。 You can store a predicate for reuse. 您可以存储谓词以供重用。

CollectionUtils.filter(collection, new Predicate(){
        boolean evaluate(Object object){return true;}
    });

You are correct, using an Iterator supports the ability to remove an object from a source collection safely, by calling remove() on the Iterator itself. 你是对的,使用Iterator支持通过在Iterator本身上调用remove()来安全地从源集合中删除对象的能力。 The point here is to avoid a ConcurrentModifiedException which implies that a collection was modified while an Iterator was open against it. 这里的要点是避免ConcurrentModifiedException,这意味着在Iterator打开它时修改了一个集合。 Some collections will let you get away with removing or adding elements to a Collection while iterating across it, but calling remove() on the Iterator is a safer practice. 有些集合可以让你在迭代时删除或添加元素,但在迭代器上调用remove()是一种更安全的做法。

But Iterator supports a derived and more powerful cousin ListIterator , only available from Lists, supports both adding and removing from a List during iteration, as well as bidirectional scrolling through Lists. 但Iterator支持派生且功能更强大的堂兄ListIterator ,仅在Lists中提供,支持在迭代期间从List添加和删除,以及双向滚动列表。

修改数据有一种错误的感觉,只需创建一个新的Iterable(或集合)并添加你想要保留的项目,其他时间在for循环中丢失((有点**)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM