了解Java迭代器 [英] Understanding Java Iterator

查看:59
本文介绍了了解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()将始终为true,因为您仍在列表的开头.

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迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆