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
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.