分析ArrayList的源码

    技术2022-05-19  25

    package java.util; public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /** * arrayList核心,数组装入元素, 下边所有的modCount表示对当前的arrayList的操作次数 */ private transient Object[] elementData; /** * 尺寸 */ private int size; /** * 根据传入的容量构造数组(ArrayList) */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); /* 初始化arrayList */ this.elementData = new Object[initialCapacity]; } /** * 默认是10个 */ public ArrayList() { this(10); } /** * 根据传入的Collection初始化ArrayList */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); //利用Collection的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 实例的容量调整为列表的当前大小。 * 应用程序可以使用此操作来最小化 ArrayList 实例的存储量。 */ public void trimToSize() { modCount++; int oldCapacity = elementData.length; if (size < oldCapacity) { // 如果当前实际大小小于分配好的大小,则通过一个数组复制,"缩小"空间 elementData = Arrays.copyOf(elementData, size); } } /** * 如有必要,增加此 ArrayList 数组的容量,以确保它至少能够容纳最小容量参数所指定的元素数。 (重要的方法!) */ public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; // 当前已经分配好的空间 if (minCapacity > oldCapacity) { // 如果发现当前的空间已经不够加入下一个元素 Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; // 通过这样的公式新开辟空间(重要的步骤!) if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); // 新的数组,数组长度为newCapacity,即新的开辟出的长度 } } public int size() { return size; } public boolean isEmpty() { return size == 0; } /** * 判断索引是否大于等于0 , 即判断了是否包含这个元素 */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 根据元素找到索引 */ public int indexOf(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; //在数组中找不到对应的元素返回-1 } /** * 最后出现的索引 */ public int lastIndexOf(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; } /** * 做一个浅复制 */ public Object clone() { try { ArrayList<E> v = (ArrayList<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** * 列表转化为数组 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } // Positional Access Operations /** * 获取 */ public E get(int index) { RangeCheck(index); // 检测是否索引越界 return (E) elementData[index]; } /** * 替换元素 */ public E set(int index, E element) { RangeCheck(index); // 检测是否索引越界 E oldValue = (E) elementData[index]; elementData[index] = element; return oldValue; //set有返回值,返回的是替换之前的值 } /** * 追加指定的元素到数组末尾 */ public boolean add(E e) { ensureCapacity(size + 1); // 查看是否需要扩充数组大小,并对总操作次数+1 elementData[size++] = e; return true; } /** * 在指定位置加入元素 */ public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); ensureCapacity(size+1); // 查看是否需要扩充数组大小,并对总操作次数+1 System.arraycopy(elementData, index, elementData, index + 1, size - index); // 把指定的index之后的数组等于全部后移一位,将指定的index位置空了出来 elementData[index] = element; // 给这个指定的已经空出来的index赋值 size++; // 尺寸肯定是要增加的 } /** * 移除对应索引的索引 */ public E remove(int index) { RangeCheck(index); // 检测是否索引越界 modCount++; E oldValue = (E) elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); // 数组全部前移,原理和上类似 elementData[--size] = null; // Let gc do its work return oldValue; } /** * 根据元素移除 */ 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; } /* * 根据索引移除元素 */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } /** * 清空数组,尺寸归零 */ public void clear() { modCount++; // Let gc do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 添加一个Collection */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // 查看是否需要扩充数组大小,并对总操作次数+1 System.arraycopy(a, 0, elementData, size, numNew); //在elementData之后接上这个集合数组 size += numNew; return numNew != 0; } /** * 在指定位置添加一个Collection */ public boolean addAll(int index, Collection<? extends E> c) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size); Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(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; } /** * 移除一个索引区间的元素 */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newSize = size - (toIndex-fromIndex); while (size != newSize) elementData[--size] = null; } /** * Checks if the given index is in range. If not, throws an appropriate * runtime exception. This method does *not* check if the index is * negative: It is always used immediately prior to an array access, * which throws an ArrayIndexOutOfBoundsException if index is negative. */ private void RangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); } /** * Save the state of the <tt>ArrayList</tt> instance to a stream (that * is, serialize it). * * @serialData The length of the array backing the <tt>ArrayList</tt> * instance is emitted (int), followed by all of its elements * (each an <tt>Object</tt>) in the proper order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out array length s.writeInt(elementData.length); // Write out all elements in the proper order. for (int i=0; i<size; i++) s.writeObject(elementData[i]); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, * deserialize it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in size, and any hidden stuff s.defaultReadObject(); // Read in array length and allocate array int arrayLength = s.readInt(); Object[] a = elementData = new Object[arrayLength]; // Read in all elements in the proper order. for (int i=0; i<size; i++) a[i] = s.readObject(); } }

    总结:

    需要注意的几个要点

    1. System.arrayCopy方法的运用

    2. Arrays.copyOf方法的使用

    3. 数组空间不够的时候是如何扩充数组的。

    4. 优点:数组索引下标查找,缺点:删除元素指定位置插入元素需要调用System.arrayCopy移动大量元素。


    最新回复(0)