Understanding Java Iterator

后端 未结 3 1719
我寻月下人不归
我寻月下人不归 2021-01-20 18:50

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 st

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-20 19:30

    It is pretty simple, actually

    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.

    When you call next(), you're moving this pointer one step ahead.

    If you don't move the pointer, hasNext() will always be true because you're still in the beginning of the list.

    So you have to call the iterator's next() until there isn't any remaining element in the list.

提交回复
热议问题