Junior — Middle
What behavior can be expected when calling the next method on an iterator object?
sobes.tech AI
Answer from AI
The next() method of an iterator object in Java returns the next element of the collection and advances the internal pointer.
Main points of next() behavior:
- If there is a next element (checked via
hasNext()),next()returns this element. - If there is no next element, calling
next()throws aNoSuchElementException.
Example:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
Always call hasNext() before next() to avoid exceptions.