Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which one of the following statements about whether an Iterator can be used a second time is true?

  • A.No; once exhausted it must be replaced by a new iterator from the collection.
  • B.Yes; calling hasNext after exhaustion rewinds it to the beginning.
  • C.Yes, but only for a list, whose iterator supports a reset.
  • D.Yes; an iterator is automatically reset when the collection is modified.

Answer: A

Correct answer: No; once exhausted it must be replaced by a new iterator from the collection.

An Iterator is a one-shot cursor with no reset: once hasNext returns false it stays false, and calling next throws NoSuchElementException. To traverse again a fresh iterator must be obtained from the collection. That is why an enhanced for loop, which creates an iterator each time, may be written repeatedly while a stored iterator may not be reused.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.