ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
Revision: 1.14
Committed: Mon Dec 5 02:56:59 2005 UTC (18 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.13: +1 -1 lines
Log Message:
copyright update for 2006

File Contents

# User Rev Content
1 dl 1.1 /*
2     * %W% %E%
3     *
4 jsr166 1.14 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5 dl 1.1 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6     */
7    
8     package java.util;
9     import java.util.*; // for javadoc (till 6280605 is fixed)
10    
11     /**
12     * Resizable-array implementation of the <tt>List</tt> interface. Implements
13     * all optional list operations, and permits all elements, including
14     * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface,
15     * this class provides methods to manipulate the size of the array that is
16     * used internally to store the list. (This class is roughly equivalent to
17     * <tt>Vector</tt>, except that it is unsynchronized.)<p>
18     *
19     * The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
20     * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
21     * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>,
22     * that is, adding n elements requires O(n) time. All of the other operations
23     * run in linear time (roughly speaking). The constant factor is low compared
24     * to that for the <tt>LinkedList</tt> implementation.<p>
25     *
26     * Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is
27     * the size of the array used to store the elements in the list. It is always
28     * at least as large as the list size. As elements are added to an ArrayList,
29     * its capacity grows automatically. The details of the growth policy are not
30     * specified beyond the fact that adding an element has constant amortized
31     * time cost.<p>
32     *
33     * An application can increase the capacity of an <tt>ArrayList</tt> instance
34     * before adding a large number of elements using the <tt>ensureCapacity</tt>
35     * operation. This may reduce the amount of incremental reallocation.
36     *
37     * <p><strong>Note that this implementation is not synchronized.</strong>
38     * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
39     * and at least one of the threads modifies the list structurally, it
40     * <i>must</i> be synchronized externally. (A structural modification is
41     * any operation that adds or deletes one or more elements, or explicitly
42     * resizes the backing array; merely setting the value of an element is not
43     * a structural modification.) This is typically accomplished by
44     * synchronizing on some object that naturally encapsulates the list.
45     *
46     * If no such object exists, the list should be "wrapped" using the
47     * {@link Collections#synchronizedList Collections.synchronizedList}
48     * method. This is best done at creation time, to prevent accidental
49     * unsynchronized access to the list:<pre>
50     * List list = Collections.synchronizedList(new ArrayList(...));</pre>
51     *
52     * <p>The iterators returned by this class's <tt>iterator</tt> and
53     * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
54     * structurally modified at any time after the iterator is created, in any way
55     * except through the iterator's own <tt>remove</tt> or <tt>add</tt> methods,
56     * the iterator will throw a {@link ConcurrentModificationException}. Thus, in
57     * the face of concurrent modification, the iterator fails quickly and cleanly,
58     * rather than risking arbitrary, non-deterministic behavior at an undetermined
59     * time in the future.<p>
60     *
61     * Note that the fail-fast behavior of an iterator cannot be guaranteed
62     * as it is, generally speaking, impossible to make any hard guarantees in the
63     * presence of unsynchronized concurrent modification. Fail-fast iterators
64     * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
65     * Therefore, it would be wrong to write a program that depended on this
66     * exception for its correctness: <i>the fail-fast behavior of iterators
67     * should be used only to detect bugs.</i><p>
68     *
69     * This class is a member of the
70     * <a href="{@docRoot}/../guide/collections/index.html">
71     * Java Collections Framework</a>.
72     *
73     * @author Josh Bloch
74     * @author Neal Gafter
75     * @version %I%, %G%
76     * @see Collection
77     * @see List
78     * @see LinkedList
79     * @see Vector
80     * @since 1.2
81     */
82    
83     public class ArrayList<E> extends AbstractList<E>
84     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
85     {
86     private static final long serialVersionUID = 8683452581122892189L;
87    
88     /**
89     * The array buffer into which the elements of the ArrayList are stored.
90     * The capacity of the ArrayList is the length of this array buffer.
91     */
92     private transient Object[] elementData;
93    
94     /**
95     * The size of the ArrayList (the number of elements it contains).
96     *
97     * @serial
98     */
99     private int size;
100    
101     /**
102     * Constructs an empty list with the specified initial capacity.
103     *
104 jsr166 1.5 * @param initialCapacity the initial capacity of the list
105     * @throws IllegalArgumentException if the specified initial capacity
106     * is negative
107 dl 1.1 */
108     public ArrayList(int initialCapacity) {
109     super();
110     if (initialCapacity < 0)
111     throw new IllegalArgumentException("Illegal Capacity: "+
112     initialCapacity);
113     this.elementData = new Object[initialCapacity];
114     }
115    
116     /**
117     * Constructs an empty list with an initial capacity of ten.
118     */
119     public ArrayList() {
120     this(10);
121     }
122    
123     /**
124     * Constructs a list containing the elements of the specified
125     * collection, in the order they are returned by the collection's
126 dl 1.2 * iterator. The <tt>ArrayList</tt> instance has an initial capacity of
127     * 110% the size of the specified collection.
128 dl 1.1 *
129     * @param c the collection whose elements are to be placed into this list
130     * @throws NullPointerException if the specified collection is null
131     */
132     public ArrayList(Collection<? extends E> c) {
133 dl 1.2 int size = c.size();
134     // 10% for growth
135     int cap = ((size/10)+1)*11;
136     if (cap > 0) {
137     Object[] a = new Object[cap];
138     a[size] = a[size+1] = UNALLOCATED;
139     Object[] b = c.toArray(a);
140     if (b[size] == null && b[size+1] == UNALLOCATED) {
141     b[size+1] = null;
142     elementData = b;
143     this.size = size;
144     return;
145     }
146     }
147     initFromConcurrentlyMutating(c);
148     }
149 jsr166 1.4
150 dl 1.2 private void initFromConcurrentlyMutating(Collection<? extends E> c) {
151     elementData = c.toArray();
152     size = elementData.length;
153     // c.toArray might (incorrectly) not return Object[] (see 6260652)
154     if (elementData.getClass() != Object[].class)
155     elementData = Arrays.copyOf(elementData, size, Object[].class);
156     }
157 jsr166 1.4
158 dl 1.2 private final static Object UNALLOCATED = new Object();
159 jsr166 1.4
160 dl 1.1 /**
161     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
162     * list's current size. An application can use this operation to minimize
163     * the storage of an <tt>ArrayList</tt> instance.
164     */
165     public void trimToSize() {
166     modCount++;
167     int oldCapacity = elementData.length;
168     if (size < oldCapacity) {
169     elementData = Arrays.copyOf(elementData, size);
170     }
171     }
172    
173     /**
174     * Increases the capacity of this <tt>ArrayList</tt> instance, if
175     * necessary, to ensure that it can hold at least the number of elements
176     * specified by the minimum capacity argument.
177     *
178 jsr166 1.5 * @param minCapacity the desired minimum capacity
179 dl 1.1 */
180     public void ensureCapacity(int minCapacity) {
181     modCount++;
182     if (minCapacity > elementData.length)
183     growArray(minCapacity);
184     }
185    
186     /**
187 jsr166 1.5 * Increases the capacity of the array.
188     *
189     * @param minCapacity the desired minimum capacity
190 dl 1.1 */
191     private void growArray(int minCapacity) {
192 dl 1.13 if (minCapacity < 0) // overflow
193     throw new OutOfMemoryError();
194 dl 1.1 int oldCapacity = elementData.length;
195     // Double size if small; else grow by 50%
196 jsr166 1.4 int newCapacity = ((oldCapacity < 64)?
197 dl 1.9 ((oldCapacity + 1) * 2):
198 dl 1.13 ((oldCapacity / 2) * 3));
199     if (newCapacity < 0) // overflow
200     newCapacity = Integer.MAX_VALUE;
201 dl 1.1 if (newCapacity < minCapacity)
202     newCapacity = minCapacity;
203     elementData = Arrays.copyOf(elementData, newCapacity);
204     }
205    
206     /**
207     * Returns the number of elements in this list.
208     *
209     * @return the number of elements in this list
210     */
211     public int size() {
212     return size;
213     }
214    
215     /**
216     * Returns <tt>true</tt> if this list contains no elements.
217     *
218     * @return <tt>true</tt> if this list contains no elements
219     */
220     public boolean isEmpty() {
221     return size == 0;
222     }
223    
224     /**
225     * Returns <tt>true</tt> if this list contains the specified element.
226     * More formally, returns <tt>true</tt> if and only if this list contains
227     * at least one element <tt>e</tt> such that
228     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
229     *
230     * @param o element whose presence in this list is to be tested
231     * @return <tt>true</tt> if this list contains the specified element
232     */
233     public boolean contains(Object o) {
234     return indexOf(o) >= 0;
235     }
236    
237     /**
238     * Returns the index of the first occurrence of the specified element
239     * in this list, or -1 if this list does not contain the element.
240     * More formally, returns the lowest index <tt>i</tt> such that
241     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
242     * or -1 if there is no such index.
243     */
244     public int indexOf(Object o) {
245     if (o == null) {
246     for (int i = 0; i < size; i++)
247     if (elementData[i]==null)
248     return i;
249     } else {
250     for (int i = 0; i < size; i++)
251     if (o.equals(elementData[i]))
252     return i;
253     }
254     return -1;
255     }
256    
257     /**
258     * Returns the index of the last occurrence of the specified element
259     * in this list, or -1 if this list does not contain the element.
260     * More formally, returns the highest index <tt>i</tt> such that
261     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
262     * or -1 if there is no such index.
263     */
264     public int lastIndexOf(Object o) {
265     if (o == null) {
266     for (int i = size-1; i >= 0; i--)
267     if (elementData[i]==null)
268     return i;
269     } else {
270     for (int i = size-1; i >= 0; i--)
271     if (o.equals(elementData[i]))
272     return i;
273     }
274     return -1;
275     }
276    
277     /**
278     * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
279     * elements themselves are not copied.)
280     *
281     * @return a clone of this <tt>ArrayList</tt> instance
282     */
283     public Object clone() {
284     try {
285     ArrayList<E> v = (ArrayList<E>) super.clone();
286     v.elementData = Arrays.copyOf(elementData, size);
287     v.modCount = 0;
288     return v;
289     } catch (CloneNotSupportedException e) {
290     // this shouldn't happen, since we are Cloneable
291     throw new InternalError();
292     }
293     }
294    
295     /**
296     * Returns an array containing all of the elements in this list
297     * in proper sequence (from first to last element).
298     *
299     * <p>The returned array will be "safe" in that no references to it are
300     * maintained by this list. (In other words, this method must allocate
301     * a new array). The caller is thus free to modify the returned array.
302     *
303     * <p>This method acts as bridge between array-based and collection-based
304     * APIs.
305     *
306     * @return an array containing all of the elements in this list in
307     * proper sequence
308     */
309     public Object[] toArray() {
310     return Arrays.copyOf(elementData, size);
311     }
312    
313     /**
314     * Returns an array containing all of the elements in this list in proper
315     * sequence (from first to last element); the runtime type of the returned
316     * array is that of the specified array. If the list fits in the
317     * specified array, it is returned therein. Otherwise, a new array is
318     * allocated with the runtime type of the specified array and the size of
319     * this list.
320     *
321     * <p>If the list fits in the specified array with room to spare
322     * (i.e., the array has more elements than the list), the element in
323     * the array immediately following the end of the collection is set to
324     * <tt>null</tt>. (This is useful in determining the length of the
325     * list <i>only</i> if the caller knows that the list does not contain
326     * any null elements.)
327     *
328     * @param a the array into which the elements of the list are to
329     * be stored, if it is big enough; otherwise, a new array of the
330     * same runtime type is allocated for this purpose.
331     * @return an array containing the elements of the list
332     * @throws ArrayStoreException if the runtime type of the specified array
333     * is not a supertype of the runtime type of every element in
334     * this list
335     * @throws NullPointerException if the specified array is null
336     */
337     public <T> T[] toArray(T[] a) {
338     if (a.length < size)
339     // Make a new array of a's runtime type, but my contents:
340     return (T[]) Arrays.copyOf(elementData, size, a.getClass());
341     System.arraycopy(elementData, 0, a, 0, size);
342     if (a.length > size)
343     a[size] = null;
344     return a;
345     }
346    
347     // Positional Access Operations
348    
349 jsr166 1.4 /**
350 dl 1.9 * Returns error message string for IndexOutOfBoundsExceptions
351 dl 1.1 */
352 dl 1.9 private String ioobe(int index) {
353     return "Index: " + index + ", Size: " + size;
354 dl 1.1 }
355    
356     /**
357     * Returns the element at the specified position in this list.
358     *
359     * @param index index of the element to return
360     * @return the element at the specified position in this list
361     * @throws IndexOutOfBoundsException {@inheritDoc}
362     */
363     public E get(int index) {
364     if (index >= size)
365 dl 1.9 throw new IndexOutOfBoundsException(ioobe(index));
366 dl 1.1 return (E)elementData[index];
367     }
368    
369     /**
370     * Replaces the element at the specified position in this list with
371     * the specified element.
372     *
373     * @param index index of the element to replace
374     * @param element element to be stored at the specified position
375     * @return the element previously at the specified position
376     * @throws IndexOutOfBoundsException {@inheritDoc}
377     */
378     public E set(int index, E element) {
379     if (index >= size)
380 dl 1.9 throw new IndexOutOfBoundsException(ioobe(index));
381 dl 1.1
382     E oldValue = (E) elementData[index];
383     elementData[index] = element;
384     return oldValue;
385     }
386    
387     /**
388     * Appends the specified element to the end of this list.
389     *
390     * @param e element to be appended to this list
391     * @return <tt>true</tt> (as specified by {@link Collection#add})
392     */
393     public boolean add(E e) {
394 jsr166 1.8 modCount++;
395 dl 1.7 int s = size;
396 dl 1.1 if (s >= elementData.length)
397     growArray(s + 1);
398     elementData[s] = e;
399 dl 1.7 size = s + 1;
400 dl 1.1 return true;
401     }
402    
403     /**
404     * Inserts the specified element at the specified position in this
405     * list. Shifts the element currently at that position (if any) and
406     * any subsequent elements to the right (adds one to their indices).
407     *
408     * @param index index at which the specified element is to be inserted
409     * @param element element to be inserted
410     * @throws IndexOutOfBoundsException {@inheritDoc}
411     */
412     public void add(int index, E element) {
413     int s = size;
414     if (index > s || index < 0)
415 dl 1.9 throw new IndexOutOfBoundsException(ioobe(index));
416 jsr166 1.8 modCount++;
417 dl 1.1 if (s >= elementData.length)
418     growArray(s + 1);
419 jsr166 1.10 System.arraycopy(elementData, index,
420 dl 1.7 elementData, index + 1, s - index);
421 dl 1.1 elementData[index] = element;
422 dl 1.7 size = s + 1;
423 dl 1.1 }
424    
425     /**
426     * Removes the element at the specified position in this list.
427     * Shifts any subsequent elements to the left (subtracts one from their
428     * indices).
429     *
430     * @param index the index of the element to be removed
431     * @return the element that was removed from the list
432     * @throws IndexOutOfBoundsException {@inheritDoc}
433     */
434     public E remove(int index) {
435     int s = size - 1;
436 jsr166 1.8 if (index > s)
437 dl 1.9 throw new IndexOutOfBoundsException(ioobe(index));
438 dl 1.1 modCount++;
439 dl 1.7 E oldValue = (E)elementData[index];
440 dl 1.1 int numMoved = s - index;
441     if (numMoved > 0)
442 jsr166 1.10 System.arraycopy(elementData, index + 1,
443 dl 1.7 elementData, index, numMoved);
444 jsr166 1.8 elementData[s] = null;
445 dl 1.7 size = s;
446     return oldValue;
447 dl 1.1 }
448    
449     /**
450     * Removes the first occurrence of the specified element from this list,
451     * if it is present. If the list does not contain the element, it is
452     * unchanged. More formally, removes the element with the lowest index
453     * <tt>i</tt> such that
454     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
455     * (if such an element exists). Returns <tt>true</tt> if this list
456     * contained the specified element (or equivalently, if this list
457     * changed as a result of the call).
458     *
459     * @param o element to be removed from this list, if present
460     * @return <tt>true</tt> if this list contained the specified element
461     */
462     public boolean remove(Object o) {
463     if (o == null) {
464     for (int index = 0; index < size; index++)
465     if (elementData[index] == null) {
466     fastRemove(index);
467     return true;
468     }
469     } else {
470     for (int index = 0; index < size; index++)
471     if (o.equals(elementData[index])) {
472     fastRemove(index);
473     return true;
474     }
475     }
476     return false;
477     }
478    
479     /*
480     * Private remove method that skips bounds checking and does not
481     * return the value removed.
482     */
483     private void fastRemove(int index) {
484     modCount++;
485     int numMoved = size - index - 1;
486     if (numMoved > 0)
487     System.arraycopy(elementData, index+1, elementData, index,
488     numMoved);
489     elementData[--size] = null; // Let gc do its work
490     }
491    
492     /**
493     * Removes all of the elements from this list. The list will
494     * be empty after this call returns.
495     */
496     public void clear() {
497     modCount++;
498    
499     // Let gc do its work
500     for (int i = 0; i < size; i++)
501     elementData[i] = null;
502    
503     size = 0;
504     }
505    
506     /**
507     * Appends all of the elements in the specified collection to the end of
508     * this list, in the order that they are returned by the
509     * specified collection's Iterator. The behavior of this operation is
510     * undefined if the specified collection is modified while the operation
511     * is in progress. (This implies that the behavior of this call is
512     * undefined if the specified collection is this list, and this
513     * list is nonempty.)
514     *
515     * @param c collection containing elements to be added to this list
516     * @return <tt>true</tt> if this list changed as a result of the call
517     * @throws NullPointerException if the specified collection is null
518     */
519     public boolean addAll(Collection<? extends E> c) {
520     Object[] a = c.toArray();
521     int numNew = a.length;
522     ensureCapacity(size + numNew); // Increments modCount
523     System.arraycopy(a, 0, elementData, size, numNew);
524     size += numNew;
525     return numNew != 0;
526     }
527    
528     /**
529     * Inserts all of the elements in the specified collection into this
530     * list, starting at the specified position. Shifts the element
531     * currently at that position (if any) and any subsequent elements to
532     * the right (increases their indices). The new elements will appear
533     * in the list in the order that they are returned by the
534     * specified collection's iterator.
535     *
536     * @param index index at which to insert the first element from the
537     * specified collection
538     * @param c collection containing elements to be added to this list
539     * @return <tt>true</tt> if this list changed as a result of the call
540     * @throws IndexOutOfBoundsException {@inheritDoc}
541     * @throws NullPointerException if the specified collection is null
542     */
543     public boolean addAll(int index, Collection<? extends E> c) {
544     if (index > size || index < 0)
545 dl 1.9 throw new IndexOutOfBoundsException(ioobe(index));
546 dl 1.1
547     Object[] a = c.toArray();
548     int numNew = a.length;
549     ensureCapacity(size + numNew); // Increments modCount
550    
551     int numMoved = size - index;
552     if (numMoved > 0)
553     System.arraycopy(elementData, index, elementData, index + numNew,
554     numMoved);
555    
556     System.arraycopy(a, 0, elementData, index, numNew);
557     size += numNew;
558     return numNew != 0;
559     }
560    
561     /**
562     * Removes from this list all of the elements whose index is between
563     * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
564     * Shifts any succeeding elements to the left (reduces their index).
565     * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
566     * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
567     *
568     * @param fromIndex index of first element to be removed
569     * @param toIndex index after last element to be removed
570     * @throws IndexOutOfBoundsException if fromIndex or toIndex out of
571     * range (fromIndex &lt; 0 || fromIndex &gt;= size() || toIndex
572     * &gt; size() || toIndex &lt; fromIndex)
573     */
574     protected void removeRange(int fromIndex, int toIndex) {
575     modCount++;
576     int numMoved = size - toIndex;
577     System.arraycopy(elementData, toIndex, elementData, fromIndex,
578     numMoved);
579    
580     // Let gc do its work
581     int newSize = size - (toIndex-fromIndex);
582     while (size != newSize)
583     elementData[--size] = null;
584     }
585    
586     /**
587     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
588     * is, serialize it).
589     *
590     * @serialData The length of the array backing the <tt>ArrayList</tt>
591     * instance is emitted (int), followed by all of its elements
592     * (each an <tt>Object</tt>) in the proper order.
593     */
594     private void writeObject(java.io.ObjectOutputStream s)
595     throws java.io.IOException{
596     // Write out element count, and any hidden stuff
597     int expectedModCount = modCount;
598     s.defaultWriteObject();
599    
600     // Write out array length
601     s.writeInt(elementData.length);
602    
603     // Write out all elements in the proper order.
604     for (int i=0; i<size; i++)
605     s.writeObject(elementData[i]);
606    
607 jsr166 1.12 if (expectedModCount != modCount) {
608 dl 1.1 throw new ConcurrentModificationException();
609     }
610    
611     }
612    
613     /**
614     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
615     * deserialize it).
616     */
617     private void readObject(java.io.ObjectInputStream s)
618     throws java.io.IOException, ClassNotFoundException {
619     // Read in size, and any hidden stuff
620     s.defaultReadObject();
621    
622     // Read in array length and allocate array
623     int arrayLength = s.readInt();
624     Object[] a = elementData = new Object[arrayLength];
625    
626     // Read in all elements in the proper order.
627     for (int i=0; i<size; i++)
628     a[i] = s.readObject();
629     }
630    
631    
632     /**
633     * Returns a list-iterator of the elements in this list (in proper
634     * sequence), starting at the specified position in the list.
635     * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
636     *
637     * The list-iterator is <i>fail-fast</i>: if the list is structurally
638     * modified at any time after the Iterator is created, in any way except
639     * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
640     * methods, the list-iterator will throw a
641     * <tt>ConcurrentModificationException</tt>. Thus, in the face of
642     * concurrent modification, the iterator fails quickly and cleanly, rather
643     * than risking arbitrary, non-deterministic behavior at an undetermined
644     * time in the future.
645     *
646     * @param index index of the first element to be returned from the
647     * list-iterator (by a call to <tt>next</tt>)
648     * @return a ListIterator of the elements in this list (in proper
649     * sequence), starting at the specified position in the list
650     * @throws IndexOutOfBoundsException {@inheritDoc}
651     * @see List#listIterator(int)
652     */
653     public ListIterator<E> listIterator(int index) {
654     if (index < 0 || index > size)
655 dl 1.9 throw new IndexOutOfBoundsException(ioobe(index));
656 dl 1.1 return new ArrayListIterator(index);
657     }
658 jsr166 1.4
659 dl 1.1 /**
660 dl 1.9 * {@inheritDoc}
661     */
662     public ListIterator<E> listIterator() {
663     return new ArrayListIterator(0);
664     }
665    
666     /**
667 dl 1.1 * Returns an iterator over the elements in this list in proper sequence.
668     *
669     * @return an iterator over the elements in this list in proper sequence
670     */
671     public Iterator<E> iterator() {
672     return new ArrayListIterator(0);
673     }
674    
675     /**
676 dl 1.9 * A streamlined version of AbstractList.ListItr
677 dl 1.1 */
678     final class ArrayListIterator implements ListIterator<E> {
679     int cursor; // index of next element to return;
680     int lastRet; // index of last element, or -1 if no such
681     int expectedModCount; // to check for CME
682    
683     ArrayListIterator(int index) {
684     cursor = index;
685     lastRet = -1;
686     expectedModCount = modCount;
687     }
688    
689     public boolean hasNext() {
690 dl 1.13 return cursor != size;
691 dl 1.1 }
692    
693     public boolean hasPrevious() {
694 dl 1.13 return cursor != 0;
695 dl 1.1 }
696    
697     public int nextIndex() {
698     return cursor;
699     }
700    
701     public int previousIndex() {
702     return cursor - 1;
703     }
704    
705     public E next() {
706 dl 1.9 try {
707 dl 1.1 int i = cursor;
708 dl 1.9 E next = get(i);
709     lastRet = i;
710     cursor = i + 1;
711     return next;
712     } catch (IndexOutOfBoundsException ex) {
713     throw new NoSuchElementException();
714     } finally {
715     if (expectedModCount != modCount)
716     throw new ConcurrentModificationException();
717 dl 1.1 }
718     }
719 jsr166 1.11
720 dl 1.1 public E previous() {
721 dl 1.9 try {
722 dl 1.1 int i = cursor - 1;
723 jsr166 1.11 E prev = get(i);
724 dl 1.9 lastRet = i;
725     cursor = i;
726 jsr166 1.11 return prev;
727 dl 1.9 } catch (IndexOutOfBoundsException ex) {
728     throw new NoSuchElementException();
729     } finally {
730 jsr166 1.12 if (expectedModCount != modCount)
731 dl 1.9 throw new ConcurrentModificationException();
732 dl 1.1 }
733     }
734    
735     public void remove() {
736     if (lastRet < 0)
737     throw new IllegalStateException();
738 jsr166 1.12 if (expectedModCount != modCount)
739 dl 1.1 throw new ConcurrentModificationException();
740     ArrayList.this.remove(lastRet);
741     if (lastRet < cursor)
742     cursor--;
743     lastRet = -1;
744     expectedModCount = modCount;
745     }
746    
747     public void set(E e) {
748     if (lastRet < 0)
749     throw new IllegalStateException();
750 jsr166 1.12 if (expectedModCount != modCount)
751 dl 1.1 throw new ConcurrentModificationException();
752     ArrayList.this.set(lastRet, e);
753     expectedModCount = modCount;
754     }
755    
756     public void add(E e) {
757 jsr166 1.12 if (expectedModCount != modCount)
758 dl 1.1 throw new ConcurrentModificationException();
759 dl 1.13 try {
760     ArrayList.this.add(cursor++, e);
761     lastRet = -1;
762     expectedModCount = modCount;
763     } catch (IndexOutOfBoundsException ex) {
764     throw new ConcurrentModificationException();
765     }
766 dl 1.1 }
767     }
768     }