/** * An ordered collection (also known as a <i>sequence</i>). The user of this * interface has precise control over where in the list each element is * inserted. The user can access elements by their integer index (position in * the list), and search for elements in the list.<p> * <p> * Unlike sets, lists typically allow duplicate elements. More formally, * lists typically allow pairs of elements <tt>e1</tt> and <tt>e2</tt> * such that <tt>e1.equals(e2)</tt>, and they typically allow multiple * null elements if they allow null elements at all. It is not inconceivable * that someone might wish to implement a list that prohibits duplicates, by * throwing runtime exceptions when the user attempts to insert them, but we * expect this usage to be rare.<p> * <p> * The <tt>List</tt> interface places additional stipulations, beyond those * specified in the <tt>Collection</tt> interface, on the contracts of the * <tt>iterator</tt>, <tt>add</tt>, <tt>remove</tt>, <tt>equals</tt>, and * <tt>hashCode</tt> methods. Declarations for other inherited methods are * also included here for convenience.<p> * <p> * The <tt>List</tt> interface provides four methods for positional (indexed) * access to list elements. Lists (like Java arrays) are zero based. Note * that these operations may execute in time proportional to the index value * for some implementations (the <tt>LinkedList</tt> class, for * example). Thus, iterating over the elements in a list is typically * preferable to indexing through it if the caller does not know the * implementation.<p> * <p> * The <tt>List</tt> interface provides a special iterator, called a * <tt>ListIterator</tt>, that allows element insertion and replacement, and * bidirectional access in addition to the normal operations that the * <tt>Iterator</tt> interface provides. A method is provided to obtain a * list iterator that starts at a specified position in the list.<p> * <p> * The <tt>List</tt> interface provides two methods to search for a specified * object. From a performance standpoint, these methods should be used with * caution. In many implementations they will perform costly linear * searches.<p> * <p> * The <tt>List</tt> interface provides two methods to efficiently insert and * remove multiple elements at an arbitrary point in the list.<p> * <p> * Note: While it is permissible for lists to contain themselves as elements, * extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt> * methods are no longer well defined on such a list. * * <p>Some list implementations have restrictions on the elements that * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting * to query the presence of an ineligible element may throw an exception, * or it may simply return false; some implementations will exhibit the former * behavior and some will exhibit the latter. More generally, attempting an * operation on an ineligible element whose completion would not result in * the insertion of an ineligible element into the list may throw an * exception or it may succeed, at the option of the implementation. * Such exceptions are marked as "optional" in the specification for this * interface. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <E> the type of elements in this list * @author Josh Bloch * @author Neal Gafter * @see Collection * @see Set * @see ArrayList * @see LinkedList * @see Vector * @see Arrays#asList(Object[]) * @see Collections#nCopies(int, Object) * @see Collections#EMPTY_LIST * @see AbstractList * @see AbstractSequentialList * @since 1.2 */
/** * The number of times this list has been <i>structurally modified</i>. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. * * <p>This field is used by the iterator and list iterator implementation * returned by the {@code iterator} and {@code listIterator} methods. * If the value of this field changes unexpectedly, the iterator (or list * iterator) will throw a {@code ConcurrentModificationException} in * response to the {@code next}, {@code remove}, {@code previous}, * {@code set} or {@code add} operations. This provides * <i>fail-fast</i> behavior, rather than non-deterministic behavior in * the face of concurrent modification during iteration. * * <p><b>Use of this field by subclasses is optional.</b> If a subclass * wishes to provide fail-fast iterators (and list iterators), then it * merely has to increment this field in its {@code add(int, E)} and * {@code remove(int)} methods (and any other methods that it overrides * that result in structural modifications to the list). A single call to * {@code add(int, E)} or {@code remove(int)} must add no more than * one to this field, or the iterators (and list iterators) will throw * bogus {@code ConcurrentModificationExceptions}. If an implementation * does not wish to provide fail-fast iterators, this field may be * ignored. */ protectedtransientintmodCount=0;
public Object get(int index) { if (index >= 0 && index < getLength()) { return item(index); } thrownewIndexOutOfBoundsException("Index: " + index); }
get() – AbstractSequentialList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * Returns the element at the specified position in this list. * * <p>This implementation first gets a list iterator pointing to the * indexed element (with <tt>listIterator(index)</tt>). Then, it gets * the element using <tt>ListIterator.next</tt> and returns it. * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { try { return listIterator(index).next(); } catch (NoSuchElementException exc) { thrownewIndexOutOfBoundsException("Index: " + index); } }
/** * Returns a list-iterator of the elements in this list (in proper * sequence), starting at the specified position in the list. * Obeys the general contract of {@code List.listIterator(int)}.<p> * <p> * The list-iterator is <i>fail-fast</i>: if the list is structurally * modified at any time after the Iterator is created, in any way except * through the list-iterator's own {@code remove} or {@code add} * methods, the list-iterator will throw a * {@code ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * * @param index index of the first element to be returned from the * list-iterator (by a call to {@code next}) * @return a ListIterator of the elements in this list (in proper * sequence), starting at the specified position in the list * @throws IndexOutOfBoundsException {@inheritDoc} * @see List#listIterator(int) */ public ListIterator<E> listIterator(int index) { checkPositionIndex(index); returnnewListItr(index); }
/** * An iterator for lists that allows the programmer * to traverse the list in either direction, modify * the list during iteration, and obtain the iterator's * current position in the list. A {@code ListIterator} * has no current element; its <I>cursor position</I> always * lies between the element that would be returned by a call * to {@code previous()} and the element that would be * returned by a call to {@code next()}. * An iterator for a list of length {@code n} has {@code n+1} possible * cursor positions, as illustrated by the carets ({@code ^}) below: * <PRE> * Element(0) Element(1) Element(2) ... Element(n-1) * cursor positions: ^ ^ ^ ^ ^ * </PRE> * Note that the {@link #remove} and {@link #set(Object)} methods are * <i>not</i> defined in terms of the cursor position; they are defined to * operate on the last element returned by a call to {@link #next} or * {@link #previous()}. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @see Collection * @see List * @see Iterator * @see Enumeration * @see List#listIterator() * @since 1.2 */ publicinterfaceListIterator<E> extendsIterator<E> { ... }
next()
1 2 3 4 5 6 7 8 9 10 11 12
/** * Returns the next element in the list and advances the cursor position. * This method may be called repeatedly to iterate through the list, * or intermixed with calls to {@link #previous} to go back and forth. * (Note that alternating calls to {@code next} and {@code previous} * will return the same element repeatedly.) * * @return the next element in the list * @throws NoSuchElementException if the iteration has no next element */ E next();
previous()
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * Returns the previous element in the list and moves the cursor * position backwards. This method may be called repeatedly to * iterate through the list backwards, or intermixed with calls to * {@link #next} to go back and forth. (Note that alternating calls * to {@code next} and {@code previous} will return the same * element repeatedly.) * * @return the previous element in the list * @throws NoSuchElementException if the iteration has no previous * element */ E previous();
/** * A thread-safe variant of {@link java.util.ArrayList} in which all mutative * operations ({@code add}, {@code set}, and so on) are implemented by * making a fresh copy of the underlying array. * * <p>This is ordinarily too costly, but may be <em>more</em> efficient * than alternatives when traversal operations vastly outnumber * mutations, and is useful when you cannot or don't want to * synchronize traversals, yet need to preclude interference among * concurrent threads. The "snapshot" style iterator method uses a * reference to the state of the array at the point that the iterator * was created. This array never changes during the lifetime of the * iterator, so interference is impossible and the iterator is * guaranteed not to throw {@code ConcurrentModificationException}. * The iterator will not reflect additions, removals, or changes to * the list since the iterator was created. Element-changing * operations on iterators themselves ({@code remove}, {@code set}, and * {@code add}) are not supported. These methods throw * {@code UnsupportedOperationException}. * * <p>All elements are permitted, including {@code null}. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code CopyOnWriteArrayList} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code CopyOnWriteArrayList} in another thread. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <E> the type of elements held in this collection * @author Doug Lea * @since 1.5 */ publicclassCopyOnWriteArrayList<E> implementsList<E>, RandomAccess, Cloneable, java.io.Serializable { ... }
public E get(int index) { rangeCheck(index); return elementData(index); }
检查是否越界,返回对应下标元素
elementData
1 2 3 4 5 6 7
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access
privatevoidgrow(int minCapacity) { // overflow-conscious code intoldCapacity= elementData.length; intnewCapacity= oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
next()
1 2 3 4 5 6 7 8 9 10 11 12
public E next() { checkForComodification(); inti= cursor; if (i >= size) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
previous()
1 2 3 4 5 6 7 8 9 10 11 12
public E previous() { checkForComodification(); inti= cursor - 1; if (i < 0) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; }
LinkedList
next()
1 2 3 4 5 6 7 8 9 10
public E next() { checkForComodification(); if (!hasNext()) thrownewNoSuchElementException();
lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; }
previous()
1 2 3 4 5 6 7 8 9
public E previous() { checkForComodification(); if (!hasPrevious()) thrownewNoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; }