Understanding Java Iterator

后端 未结 3 1749
我寻月下人不归
我寻月下人不归 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:22

    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");
          }
    }
    

提交回复
热议问题