一 概述
public class ArrayList<E> extends AbstractList<E> implements List<E>, Randomaccess, Cloneable, java.io.Serializable
可見它實現List接口,其底層使用數組保存所有元素,其操作基本上是對數組的操作。
此實現不是同步的。如果多個線程同時訪問一個ArrayList實例,而其中至少一個線程從結構上修改了列表,那么它必須 保持外部同步。
二 具體實現
2.1 原始數組
PRivate transient Object[] elementData;transient關鍵字表示變量不會被序列化。為何使用該關鍵字?由于在ArrayList中的elementData這個數組的長度是變長的,java在擴容的時候,有一個擴容因子,也就是說這個數組的長度是大于等于ArrayList的長度的,我們不希望在序列化的時候將其中的空元素也序列化到磁盤中去,所以需要手在調用writeObject()時手動序列化數組對象。
2.2 構造方法
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } public ArrayList() { this(10); } 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); }總共3個構造方法,可以構造一個默認初始容量為10的空列表、構造一個指定初始容量的空列表以及構造一個包含指定collection的元素的列表,這些元素按照該collection的迭代器返回它們的順序排列的。2.3 trimToSize()
調用copyOf返回有效長度的ArrayList();
public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }使用一個臨時數組暫存,再返回該臨時數組。copyOf后得到的數組與原數組存儲地址不同。修改后相互不影響。2.4 ensureCapacity()
調用grow();
2.5 grow()
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); }每次增長為原來的1.5倍,調用Arrays.copyOf()完成。2.6 indexOf()
調用equals()方法。
2.7 clone()和toArray()
public Object clone() { try { @SuppressWarnings("unchecked") 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); }調用Arrays.copyOf();
新聞熱點
疑難解答