❓ What happens if you call iterator.next()
without hasNext()
?
👉 Answer:
If there is a next element, then next()
simply returns it — no problem.
But if the iterator is already at the end, and you don’t check hasNext()
, then calling next()
will throw:
⚠️
java.util.NoSuchElementException
example
List<String> list = List.of("A", "B");
Iterator<String> it = list.iterator();
System.out.println(it.next()); // "A"
System.out.println(it.next()); // "B"
System.out.println(it.next()); // 💥 NoSuchElementException
There’s no hasNext()
check here — so next()
is blindly called after the last element.
🧠 So, is hasNext()
required?
Technically, no — Java won’t stop you from calling next()
directly. But:
- You should always use
hasNext()
to check before callingnext()
. - It’s defensive programming: you avoid errors by confirming there’s something to get.
✅ Safe Looping Pattern:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next(); // always safe
System.out.println(item);
}
💬 Summary
Action | Result |
---|---|
hasNext() → true + next() | ✅ Returns next element |
hasNext() → false + next() | ❌ Throws NoSuchElementException |
Call next() without hasNext() | Risky — may crash if no next |