Java.Collections.How many elements will be skipped if Iterator.next() is called after 10 calls to Iterator.hasNext()?

👉 Answer:

None. Zero elements are skipped.


🔍 Why?

Because:

  • hasNext() is a peek method — it does not move the iterator forward.
  • Only next() advances the iterator to the next element.

So no matter how many times you call hasNext():

it.hasNext();
it.hasNext();
it.hasNext();
// Still pointing to the first element

When you finally call:

it.next(); // ✅ Returns the first element

You get the same first element, as if you’d only called hasNext() once.

🧪 Tiny Example:

List<String> list = List.of("A", "B", "C");
Iterator<String> it = list.iterator();

for (int i = 0; i < 10; i++) {
    System.out.println(it.hasNext()); // true printed 3 times, then false
}

System.out.println(it.next()); // 💥 Only safe the first 3 times

If the iterator has only 3 elements, only 3 next() calls are safe — doesn’t matter how many times hasNext() is called.

This entry was posted in Без рубрики. Bookmark the permalink.