Home

iteratorhasNext

Iterator hasNext is a method commonly found in iterator interfaces that reports whether more elements remain to be traversed. It is a predicate and generally does not advance the iteration; it answers the question of whether a next element exists.

In Java, the typical example is the java.util.Iterator interface, which defines hasNext() and next(). The common

Semantics and guarantees vary by language and implementation. If hasNext() returns true, a call to next() should

Other languages use different names or constructs for a similar concept. For example, Python iterations rely

usage
pattern
is
while
(it.hasNext())
{
Object
o
=
it.next();
}.
hasNext
may
reflect
the
current
state
of
the
underlying
collection,
and
some
implementations
can
throw
a
concurrent
modification
exception
if
the
collection
is
altered
during
iteration.
Conventions
vary,
but
hasNext
is
expected
to
be
safe
to
call
multiple
times
before
a
subsequent
next().
yield
the
next
element,
and
if
hasNext()
returns
false,
calling
next()
should
throw
a
NoSuchElementException
(in
languages
with
that
contract).
Some
iterators
may
prefetch
or
look
ahead
to
determine
availability,
which
can
affect
performance
characteristics.
on
StopIteration
raised
by
the
iterator,
rather
than
a
hasNext-like
check,
while
C#
uses
MoveNext()
on
IEnumerator,
which
advances
the
sequence
and
returns
whether
a
next
element
exists.
The
exact
contract
of
hasNext
and
its
alternatives
depends
on
the
language
and
library
in
use.