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
If you remove the if statement, then it will go for an infinite loop since your iterator.next()
is in the if condition. Actually iterator.next()
is the api that moves the pointer, not the hasNext()
. hasNext()
just checks if there is any element in the collection. Since removal of the if statement is also removing the hasNext
api, the pointer to the collection is not moving and hasNext
is always returning true.
If you take out the iterator.next()
from the if condition and move it above the if condition, then the loop will iterate for 5 times even after you remove the if statement.
Iterator iterator = collection1.iterator();
while(iterator.hasNext()){
String currentColor = iterator.next();
if(collection2.contains(currentColor)){
System.out.println("duplicate");
}
}