Understanding Java Iterator(了解 Java 迭代器)
问题描述
如果我运行以下代码,它将打印出 3 次重复,但是当我删除 while 循环内的 if 语句(只是为了查看它会迭代多少次)时,它会启动一个无限循环.
If I run the following code, it will print out 3 times duplicate, but when I remove the if statement inside the while loop (just to see how many times it will iterate) it starts an infinite loop.
这个 hasNext()
方法实际上是如何工作的?我认为这只会迭代 5 次,因为列表中有 5 个项目.
How does actually this hasNext()
method working? I thought that will iterate only 5 times as I have 5 items in the list.
public class ExerciseOne {
public static void main(String []args){
String []colors = {"MAGENTA","RED","WHITE","BLUE","CYAN"};
List<String> list = new ArrayList<String>();
for(String color : colors)
list.add(color);
String[] removeColors = {"RED","WHITE","BLUE"};
List<String> removeList = new ArrayList<String>();
for(String color : removeColors)
removeList.add(color);
removeColors(list,removeList);
System.out.printf("%n%nArrayList after calling removeColors:%n");
for(String color : list)
{
System.out.printf("%s ",color);
}
}
private static void removeColors(Collection<String> collection1, Collection<String> collection2)
{
Iterator<String> iterator = collection1.iterator();
while(iterator.hasNext()){
if(collection2.contains(iterator.next()))
System.out.println("duplicate");
}
}
}
推荐答案
其实很简单
while(iterator.hasNext()){
if(collection2.contains(iterator.next()))
System.out.println("duplicate");
}
想象一下迭代器是一个指向列表元素的指针.
Imagine that the iterator is a pointer to an element of your list.
当您调用 next()
时,您将指针向前移动了一步.
When you call next()
, you're moving this pointer one step ahead.
如果您不移动指针,则 hasNext()
将始终为真,因为您仍在列表的开头.
If you don't move the pointer, hasNext()
will always be true because you're still in the beginning of the list.
所以你必须调用迭代器的 next()
直到列表中没有任何剩余元素.
So you have to call the iterator's next()
until there isn't any remaining element in the list.
这篇关于了解 Java 迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:了解 Java 迭代器
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01