Everyone explained pretty well on it. Let me answer when should this class be used.
When Should You Use NoSuchElementException?
Java includes a few different ways to iterate through elements in a collection. The first of these classes, Enumeration, was introduced in JDK1.0
and is generally considered deprecated in favor of newer iteration classes, like Iterator and ListIterator.
As with most programming languages, the Iterator class includes a hasNext()
method that returns a boolean indicating if the iteration has anymore elements. If hasNext()
returns true
, then the next()
method will return the next element in the iteration. Unlike Enumeration, Iterator also has a remove()
method, which removes the last element that was obtained via next()
.
While Iterator is generalized for use with all collections in the Java Collections Framework
, ListIterator
is more specialized and only works with List-based collections, like ArrayList
, LinkedList
, and so forth. However, ListIterator
adds even more functionality by allowing iteration to traverse in both directions via hasPrevious()
and previous()
methods.