Java Reference
In-Depth Information
Iterator
superinterfaceinthat
ListIterator
providesmethodsforiteratingover
alistineitherdirection,modifyingthelistduringiteration,andobtainingtheiterator's
current position in the list.
Note
The
Iterator
and
ListIterator
instances that are returned by the
iterator()
and
listIterator()
methods in the
ArrayList
and
LinkedList List
implementation classes are
fail-fast
: when a list is structurally
modified(bycallingtheimplementation's
add()
methodtoaddanewelement,forex-
ample)aftertheiteratoriscreated,inanywayexceptthroughtheiterator'sown
add()
or
remove()
methods, theiterator throws
ConcurrentModificationExcep-
tion
.Therefore,inthefaceofconcurrentmodification,theiteratorfailsquicklyand
cleanly,ratherthanriskingarbitrary,nondeterministicbehavioratsometimeinthefu-
ture.
ListIterator
declares the following methods:
•
void add(E e)
inserts
e
intothelistbeingiteratedover.Thiselementisin-
sertedimmediatelybeforethenextelementthatwouldbereturnedby
next()
,
if any, and after the next element that would be returned by
previous()
,
if any. This method throws
UnsupportedOperationException
when
thislistiteratordoesnotsupport
add()
,
ClassCastException
when
e
's
classisinappropriateforthislist,and
IllegalArgumentException
when
some property of
e
prevents it from being added to this list.
•
boolean hasNext()
returnstruewhenthislistiteratorhasmoreelements
when traversing the list in the forward direction.