Home

javautilIterator

The java.util.Iterator interface is part of the Java standard library and provides a uniform way to traverse the elements of a collection in a forward direction. It is generic, declared as Iterator<E>, and is implemented by most Java collection classes such as ArrayList, LinkedList, HashSet, and the views of maps.

The core methods of Iterator are hasNext(), next(), and remove() (where remove is optional). hasNext() returns true

Usage typically involves obtaining an iterator from a collection via collection.iterator(), then looping while hasNext() is

Many iterators are fail-fast: if the underlying collection is structurally modified after the iterator is created

Notes: Iterator traverses elements forward only; to traverse bidirectionally, ListIterator offers additional capabilities. Implementations may vary

if
there
are
more
elements
to
traverse.
next()
returns
the
next
element
and
advances
the
iterator;
it
throws
NoSuchElementException
if
there
are
no
further
elements.
remove()
removes
the
last
element
returned
by
next;
it
is
an
optional
operation
and
may
throw
IllegalStateException
if
next
has
not
yet
been
called
or
if
remove
has
already
been
called
after
the
last
next,
or
UnsupportedOperationException
if
the
underlying
iterator
does
not
support
removal.
true
and
calling
next()
to
process
each
element.
The
remove
method
can
be
used
to
delete
elements
from
the
underlying
collection
during
iteration.
The
enhanced
for
loop
(for-each)
uses
an
Iterator
under
the
hood
and
provides
a
more
concise
way
to
iterate.
(except
through
the
iterator’s
own
remove
method),
a
ConcurrentModificationException
may
be
thrown
on
a
subsequent
operation.
in
behavior
and
performance
characteristics,
but
the
contract
remains
consistent
across
standard
Java
collections.