/** * 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. */transientObject[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * * @serial */privateint size;
2.2 构造函数
/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throwsIllegalArgumentException if the specified initial capacity * is negative */publicArrayList(int initialCapacity) {if (initialCapacity >0) {this.elementData=newObject[initialCapacity]; } elseif (initialCapacity ==0) {this.elementData= EMPTY_ELEMENTDATA; } else {thrownewIllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. */publicArrayList() {this.elementData= DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throwsNullPointerException if the specified collection is null */publicArrayList(Collection<? extends E> c) { elementData =c.toArray();if ((size =elementData.length) !=0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() !=Object[].class) elementData =Arrays.copyOf(elementData, size,Object[].class); } else {// replace with empty array.this.elementData= EMPTY_ELEMENTDATA; } }
/** * Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */publicvoidensureCapacity(int minCapacity) {int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)// any size if not default element table?0// larger than default for default empty table. It's already// supposed to be at default size.: DEFAULT_CAPACITY;if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity); } }privatevoidensureCapacityInternal(int minCapacity) {if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity =Math.max(DEFAULT_CAPACITY, minCapacity); }ensureExplicitCapacity(minCapacity); }privatevoidensureExplicitCapacity(int minCapacity) { modCount++;// overflow-conscious codeif (minCapacity -elementData.length>0)grow(minCapacity); } /** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */privatestaticfinalint MAX_ARRAY_SIZE =Integer.MAX_VALUE-8; /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */privatevoidgrow(int minCapacity) {// overflow-conscious codeint oldCapacity =elementData.length;int newCapacity = 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); }privatestaticinthugeCapacity(int minCapacity) {if (minCapacity <0) // overflowthrownewOutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE: MAX_ARRAY_SIZE; }
2.4 add(), addAll()
跟C++ 的vector不同,ArrayList没有push_back()方法,对应的方法是add(E e),ArrayList也没有insert()方法,对应的方法是add(int index, E e)。这两个方法都是向容器中添加新元素,这可能会导致capacity不足,因此在添加元素之前,都需要进行剩余空间检查,如果需要则自动扩容。扩容操作最终是通过grow()方法完成的。
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */publicbooleanadd(E e) {ensureCapacityInternal(size +1); // Increments modCount!! elementData[size++] = e;returntrue; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throwsIndexOutOfBoundsException {@inheritDoc} */publicvoidadd(int index,E element) {rangeCheckForAdd(index);ensureCapacityInternal(size +1); // Increments modCount!!System.arraycopy(elementData, index, elementData, index +1, size - index); elementData[index] = element; size++; }
add(int index, E e)需要先对元素进行移动,然后完成插入操作,也就意味着该方法有着线性的时间复杂度。
/** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the * specified collection's Iterator. The behavior of this operation is * undefined if the specified collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified collection is this list, and this * list is nonempty.) * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throwsNullPointerException if the specified collection is null */publicbooleanaddAll(Collection<? extends E> c) {Object[] a =c.toArray();int numNew =a.length;ensureCapacityInternal(size + numNew); // Increments modCountSystem.arraycopy(a,0, elementData, size, numNew); size += numNew;return numNew !=0; } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throwsIndexOutOfBoundsException {@inheritDoc} * @throwsNullPointerException if the specified collection is null */publicbooleanaddAll(int index,Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a =c.toArray();int numNew =a.length;ensureCapacityInternal(size + numNew); // Increments modCountint numMoved = size - index;if (numMoved >0)System.arraycopy(elementData, index, elementData, index + numNew, numMoved);System.arraycopy(a,0, elementData, index, numNew); size += numNew;return numNew !=0; }
/** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */publicvoidtrimToSize() { modCount++;if (size <elementData.length) { elementData = (size ==0)?EMPTY_ELEMENTDATA:Arrays.copyOf(elementData, size); } }
2.9 indexOf(), lastIndexOf()
获取元素的第一次出现的index:
/** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. */publicintindexOf(Object o) {if (o ==null) {for (int i =0; i < size; i++)if (elementData[i]==null)return i; } else {for (int i =0; i < size; i++)if (o.equals(elementData[i]))return i; }return-1; }
获取元素的最后一次出现的index:
/** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. */publicintlastIndexOf(Object o) {if (o ==null) {for (int i = size-1; i >=0; i--)if (elementData[i]==null)return i; } else {for (int i = size-1; i >=0; i--)if (o.equals(elementData[i]))return i; }return-1; }