Java Reference
In-Depth Information
102
public Iterator<AnyType> iterator( )
103
{ return new ArrayListIterator( 0 ); }
104
105
public ListIterator<AnyType> listIterator( int idx )
106
{ return new ArrayListIterator( idx ); }
107
108
// This is the implementation of the ArrayListIterator
109
private class ArrayListIterator implements ListIterator<AnyType>
110
{
111
private int current;
112
private int expectedModCount = modCount;
113
private boolean nextCompleted = false;
114
private boolean prevCompleted = false;
115
116
ArrayListIterator( int pos )
117
{
118
if( pos < 0 || pos > size( ) )
119
throw new IndexOutOfBoundsException( );
120
current = pos;
121
}
122
123
public boolean hasNext( )
124
{
125
if( expectedModCount != modCount )
126
throw new ConcurrentModificationException( );
127
return current < size( );
128
}
129
130
public boolean hasPrevious( )
131
{
132
if( expectedModCount != modCount )
133
throw new ConcurrentModificationException( );
134
return current > 0;
135
}
figure 15.15
ArrayList
implementation
(part 3)
when an instance of the iterator is created (immediately prior to calling the
constructor);
modCount
is a shorthand for
ArrayList.this.modCount
. The two
Boolean instance members that follow are flags used to verify that a call to
remove
is legal.
The
ArrayListIterator
constructor is declared package visible; thus it is
usable by the
ArrayList
. Of course it could be declared public, but there is no
reason to do so and even if it were private, it would still be usable by
ArrayList
.
Package visible, however, seems most natural in this situation. Both
hasNext
and
hasPrevious
verify that there have been no external structural modifications
since the iterator was created, throwing an exception if the
ArrayList modCount
does not match the
ArrayListIterator expectedModCount
.
Search WWH ::
Custom Search