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 迭代器
基础教程推荐
- JPA惰性列表上的流 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
