Eli*_*luf 3 java collections iterator
在关于集合的Oracle教程https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html中, 我看到以下内容:
Use Iterator instead of the for-each construct when you need to:
1. Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
2. Iterate over multiple collections in parallel.
Run Code Online (Sandbox Code Playgroud)
我理解第一个选项'删除当前元素',它由迭代器支持,并且不受for-each构造的支持.我需要澄清第二个选项'并行迭代多个集合',这可以用迭代器而不是for-each来完成.有人可以提供这种情况的一个例子吗?据我所知,for-each也可以嵌套,因此可以并行访问多个集合.
这不是Iterator vs For-Each 和Iterator vs的重复, 因为他们询问迭代器和for-each的一般比较,我问oracle教程中的特定句子.
假设您有两个集合:
List<A> listA = /*...*/;
List<B> listB = /*...*/;
Run Code Online (Sandbox Code Playgroud)
...并且你需要并行迭代它们(也就是说,处理每个条目中的第一个条目,然后处理每个条目中的下一个条目等).你不能用增强for
循环来做,你会使用Iterator
s :
Iterator<A> itA = listA.iterator();
Iterator<B> itB = listB.iterator();
while (itA.hasNext() && itB.hasNext()) {
A nextA = itA.next();
B nextB = itB.next();
// ...do something with them...
}
Run Code Online (Sandbox Code Playgroud)
公平地说,您可以将增强for
循环与迭代器结合使用:
Iterator<A> itA = listA.iterator();
for (B nextB : listB) {
if (!itA.hasNext()) {
break;
}
A nextA = itA.next();
// ...do something with them...
}
Run Code Online (Sandbox Code Playgroud)
......但是它的笨拙和清晰度受到影响,只有其中一个系列可以成为其中的主题for
,其余的必须是Iterator
s.
归档时间: |
|
查看次数: |
43 次 |
最近记录: |