ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
Revision: 1.22
Committed: Mon Jun 26 01:38:57 2006 UTC (17 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.21: +0 -10 lines
Log Message:
sync with mustang

File Contents

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