一、ArrayList构造函数
/** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** * 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 * @throws NullPointerException if the specified collection is null */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
ArrayList提供了三个构造函数,第一个是无参的,从其注释来看Constructs an empty list with an initial capacity of ten.从其实际方法来看,构造函数刚开始的时候,只是一个空的数组,其长度并不是为10,由此可以推测,它采用的是懒加载的形式对数组进行初始化,在代码的add方法扩容的时候得到验证;第二个是指定ArrayList初始容量大小的构造函数,当指定的容量小于10的时候,在懒加载使用到的时候,会将其扩展到最小的容量10然后再进行相应的添加元素操作。第三个是将一个集合作为参数的构造函数,从其代码实现来看,集合与集合之间的转换,是先转换成数组,再对数组进行相应的操作。
二、ArrayLst往集合添加元素
ArrayList提供了四个添加元素的方法,分别为在集合末尾添加元素add(E e),在指定的集合索引位置添加元素add(int index, E element),在集合末尾添加集合 addAll(Collection<? extends E> c),在集合指令的索引位置添加另一个集合addAll(int index, Collection<? extends E> c)。
1、集合末尾添加元素add(E e)
首先会确保集合中容量的大小,再往往集合末尾添加元素,如果容量不满足要求,则需要对集合进行扩容。
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
如果集合对应的容器数组elementData为空,则elementData应该具有的最小容量minCapacity为,默认容量10与集合元素个数size+1两者比较的最大值。
private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
如果容器数组elementData长度达不到其需要的最小长度minCapacity,则需要进行扩容。
private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
先将容量扩成原来容量的1.5倍,扩容后的容量newCapacity如果大于需要的最小容量minCapacity则直接使用,如果扩容后的容量还未达到最小容量minCapacity,则将数组的容量扩大为minCapacity,但是这个扩展后的容量,有一个最大值上限,超过这个最大值上限Integer.MAX_VALUE(也就是minCapacity < 0,因为大于这个以后Integer.MAX_VALUE的值为负数)会内存溢出错误OutOfMemoryError。容量确定后会重新将容器elementData中的元素复制到一个新的数组中,将elementData的引用地址进行更新。
private void grow(int minCapacity) { // overflow-conscious code int 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); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
2、集合指定位置添加元素 add(int index, E element)
这个比在末尾添加元素操作的步骤要多许多,首先进行范围检查,如果index大于size或者小于0,则抛出越界异常; 接下来再进行扩容,扩容之后,还要使用System.arraycopy进行复制,比起在集合末尾添加元素数组需要复制1次,在指定位置添加元素数组一般得复制3次,一次发生在扩容的时候,剩下两次发生在System.arraycopy,因为是使用同一个数组进行复制,内部会产生临时数组进行复制操作。
/** * 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 * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
3、集合末尾添加集合元素addAll(Collection<? extends E> c)
首先将要添加的元素转换成一个数组,然后进行扩容,扩容之后,使用System.arraycopy进行复制追加元素。
/** * 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 * @throws NullPointerException if the specified collection is null */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; }
4、集合指定位置添加集合元素addAll(int index, Collection<? extends E> c)
首先对下标进行范围检查看是否越界,接下来将集合转换成要被复制的数组a,并对原集合的数组elementData进行扩容,再接下来就是复制元素。如果index<elementData.size,相当于是在数组elementData中间插入数组a,则需要将元数组elementData下标为index后的元素进行移位,腾出相应的空间System.arraycopy(elementData, index, elementData, index + numNew,numMoved);然后再将新加入的元素复制到已移位元素的对应位置System.arraycopy(a, 0, elementData, index, numNew);如果index不小于size,则System.arraycopy(a, 0, elementData, index, numNew);直接进行复制。
/** * 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 * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int 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; }
三、ArrayList删除元素
ArrayList中删除元素,可分为按下标删除对象remove(int),按对象删除remove(object),删除某个子集removeAll(Collection<?>),保留某个子集retainAll(Collection<?>),清除所有元素clear()。
1、按下标删除元素remove(int)
首先检查数组下标是否越界,接下来根据数组下标获取要删除的元素,并计算出删除元素以后,需要移动的元素个数int numMoved = size - index - 1;接下来通过复制数组的形式,将要删除元素下标的位置往前挪一位System.arraycopy(elementData, index+1, elementData, index,numMoved); 全部覆盖达到删除元素目的,元素删除后,将最后一个空出来的位置设置成null,更利于垃圾回收,最后返回被删除的元素。
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
2、按对象删除元素remove(Object)
首先循环遍历数组,找到元素所在的下标,然后再按照remove(int)的方法删除元素,并返回成功与否,注意,如果ArrayList中有多个相同的值,该方法只能删除其找到的第一个值进行删除。
/** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
3、按集合删除元素removeAll(Collection<?>)
ArrayList中删除一个集合,相当于求两个集合的差集。如:a.removeAll(b),即为a-b。
4、求两个集合的交集retainAll(Collection<?>)
ArrayList中retainAll一个集合,相当于求两个集合的交集。a.retainAll(b),即a与b的交集。
求两个集合的差集和交集,都使用同一个方法,batchRmove(boolean),传入为false时,表示求差集,传入为true时表示求交集,使用ArrayList时,所求的差集和交集是不会去重的,可能存在重复元素的情况。源码如下,首先通过循环遍历集合A,判断在不在集合B中,求差集的时候,将不在B中的元素保留下来,求交集的时候,将在B中的元素保留在原数组中。最后将剩余的其他元素全部置为空,从而达到求差集或交集的目的。该方法对于不同类型的集合也适用。
private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
三、ArrayList元素的获取和查询
ArrayList集合当中,要获取一个元素可以使用get(index),要循环遍历集合中的每一个元素,可以使用for循环进行遍历,也可以使用迭代器Iterator实现的foreach循环进行遍历,本小节主要讲一下ArrayList中是如何实现迭代器的。迭代器是一个单向的对集合进行遍历的工具,其提供了hasNext(),next(),remove()三个方法。由于ArrayList底层是通过数组实现的,当ArrayList在做增删的时候,实际上是改变了底层数组的结构的,迭代器不允许在迭代的过程中,底层数组的结构受到更改,它有用到一个变量modCount来标记,每当ArrayList对元素做1次增或者删的时候,modCount都会加1,当迭代器记录的modCount数量expectedModCount与新的modCount不相等的时候,则抛出并发操作异常。另外迭代器还用到一个变量游标cursor来表示,其迭代过程中的下标值,同时还提供一个变量lastRet来标记最后一次迭代到的元素的下标,为remove()方法提供删除的下标。在迭代的过程中,要删除元素,必须使用迭代器的remove()方法,如果使用ArrayList的remove()方法,则会破坏迭代的数据结构,出现异常。迭代的remove()方法还必须放在next()方法的后面,否则不能删除元素,还会抛出IllegalStateException异常。
/** * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
浙公网安备 33010602011771号