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
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01