了解 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.
相关文章