本文基於jdk1.8
Java Collection庫中有三類:List,Queue,Set
其中List,有三個子實現類:ArrayList,Vector,LinkedList
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/ArrayList.java
實現原理
transient Object[] elementData; // 存放元素的數組 private int size; // 實際存放元素的數量
ArrayList底層是使用一個Object類型的數組來存放數據的,size變量代表List實際存放元素的數量
add,remove,get,set,contains操作
get和set方法,都是通過數組下標,直接操作數據的,時間復雜度為O(1)
public boolean contains(Object o) { return indexOf(o) >= 0; } public int indexOf(Object o) { // 遍歷所有元素找到相同的元素,返回元素的下標, // 如果是元素為null,則直接比較地址,否則使用equals的方法比較 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; }
add
public boolean add(E e) { ensureCapacityInternal(size + 1); // 擴容檢測 elementData[size++] = e; //新增元素添加到末尾 return true; } public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // 擴容檢測 // 使用System.arraycopy的方法,將index后面元素往后移動1位 System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; // 存放元素到index位置 size++; }
remove
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; // 方便JVM進行GC操作,避免出現泄露 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; // clear to let GC do its work }
removeRange
protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; }
removeAll
public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); } 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; }
retainAll
public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); }
get
public E get(int index) { rangeCheck(index); return elementData(index); }
set
public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
trimToSize()
public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } }
由於elementData的長度會被拓展,size標記的是其中包含的元素的個數。所以會出現size很小但elementData.length很大的情況,將出現空間的浪費。trimToSize將返回一個新的數組給elementData,元素內容保持不變,length很size相同,節省空間。
clear
public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
擴容策略
ArrayList底層是使用數組存儲的,當數組大小不足存放新增元素的時候,才會發生擴容。
在add操作中,ArrayList首先會調用ensureCapacityInternal方法進行擴容檢測的。
如果數組大小不足,則會自動擴容;如果擴容后的大小超出數組最大的大小,則會拋出異常。
ensureCapacityInternal(size + 1);
ArrayList擴容方案,主要有兩個步驟:1.大小檢測,2.擴容
-
大小檢測:
-
檢測數組大小是否為0,如果是,則使用默認的擴容大小10
-
檢測是否需要擴容,只有當數組最小需要容量大小大於當前數組大小時,才會進行擴容
-
-
擴容:grow和hugeCapacity
-
進行數組越界判斷
-
拷貝原始數據到新的數組中
-
private void ensureCapacityInternal(int minCapacity) { // 通過ArrayList<Integer> a = new ArrayList<Integer>()或者通過序列化讀取,元素大小為0時,底層數組才會為null數組 // 如果底層數組大小為0,則使用默認的容量大小10 if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { // 數據結構發生改變,和fail-fast機制有關,在使用迭代器過程中,只能通過迭代器的方法(比如迭代器中add,remove等),修改List的數據結構, // 如果使用List的方法(比如List中的add,remove等),修改List的數據結構,會拋出ConcurrentModificationException modCount++; // 當前數組容量大小不足時,才會調用grow方法,自動擴容 if (minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // 新的容量大小 = 原容量大小的1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) //溢出判斷,比如minCapacity = Integer.MAX_VALUE / 2, oldCapacity = minCapacity - 1 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; }
fail-fast機制的實現
fail-fast機制也叫作”快速失敗”機制,是Java集合中的一種錯誤檢測機制。
在對集合進行迭代過程中,除了迭代器可以對集合進行數據結構上進行修改,其他的對集合的數據結構進行修改,都會拋出ConcurrentModificationException錯誤。
這里,所謂的進行數據結構上進行修改,是指對存儲的對象,進行add,set,remove操作,進而對數據發生改變。
ArrayList中,有個modCount的變量,每次進行add,set,remove等操作,都會執行modCount++。
在獲取ArrayList的迭代器時,會將ArrayList中的modCount保存在迭代中,
每次執行add,set,remove等操作,都會執行一次檢查,調用checkForComodification方法,對modCount進行比較。
如果迭代器中的modCount和List中的modCount不同,則拋出ConcurrentModificationException
final void checkForComodification() { if (expectedModCount != ArrayList.this.modCount) throw new ConcurrentModificationException(); }
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(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
序列化
transient Object[] elementData;
// non-private to simplify nested class access
transient修飾符讓elementData無法自動序列化,這樣的原因是,數組內存儲的的元素其實只是一個引用,單單序列化一個引用沒有任何意義,反序列化后這些引用都無法在指向原來的對象。ArrayList使用writeObject()實現手工序列化數組內的元素。
/** * 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 size as capacity for behavioural compatibility with clone() s.writeInt(size); // 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 { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } }
使用場景
ArrayList的使用場景主要從其優缺點來考慮的:
優點:
get,set,時間復雜度為O(1)
add(一般都是在末尾插入),時間復雜度為O(1),最差情況下(往頭部插入數據),時間復雜度O(n)
數據存儲是順序的
缺點:
remove,時間復雜度為O(n),最優情況下(移除末尾元素),時間復雜度為O(1)
ArrayList底層使用數組存儲數據,數組是不能自動擴容的,因此在發生擴容的情況下,需要移動大量的元素。
ArrayList大小很大的時候,會存在空間浪費(可以通過trimToSize方法,清除空閑空間)
數組大小是由限制的,受jvm和機器的影響,當擴容超出上限時,ArrayList會拋出異常
插入操作多,數據量不大,順序存儲時,可以考慮使用ArrayList
多線程情況下:
ArrayList所有的操作,都不是同步的,因此ArrayList不是線程安全的。
如果考慮到線程安全的話,可以使用CopyOnWriteArrayList或者外部同步ArrayList(List list = Collections.synchronizedList(new ArrayList(…));)
思考
1.remove方法中,為什么會將數組對應的元素置為null?
ArrayList內部使用數組實現一套管理對象的機制,remove操作中,已經將元素的數量-1了,ArrayList認為該對象已經被移除了,應該被jvm回收。
但是,對於jvm來說,該值仍然保存在數組中,ArrayList持有這個對象的引用,在jvm發生GC時,這個對象是不對被jvm回收,這樣就會造成內存泄露了。
2.查找元素的方法中(比如indexOf),為什么需要對元素進行null值判斷?
判斷對象是否相等,有兩個方面,1.對象存儲的地址;2.對象的內容。
==,是用來比較兩個對象的地址是否相等,一般來說,兩個對象的地址相同,那么這兩個對象可以認為是相同的對象
equals方法,是用來比較對象內容的,當然,也可以重載該方法,直接比較對象地址;Object對象的equals方法,是比較地址的。
一般來說,重載equals方法的同時,也要重載hashCode方法的,重載hashCode方法,必須得遵守6個原則:
-
自反性:對於任何非null的引用值x,x.equals(x),必須返回true
-
傳遞性:對於任何非null的引用值x,y,z,如果x.equals(y) 為true,且y.equals(z)為true,那么x.equals(z)必須為true
-
對稱性:對於任何非null的引用值x,y,如果x.equals(y)為true,那么y.equals(x)必須為true
-
非空性:對於任何非null的引用值x,x.equals(null)必須為false
-
一致性:對於任何非null的引用值x,y,如果多次調用equals方法,如果x和y比較的值沒有改變,那么x.equals(y)就會一致性返回true或者false
為什么重載equals方法,一般要重載hashCode方法?
重載equals方法,可以不重載hashCode方法,但是一般情況,不建議這么做。
hashCode方法,使用來求出對象的Hash值,
重載hashCode方法主要是為了提高一些容器(比如HashMap,Hashtable)進行hash運算的效率,而且也可以避免出現一些錯誤(比如HashSet容器的操作)
對於元素進行null值判斷,我認為主要是為了效率考慮,如果是null值的話,可以直接比較地址,而非空值,則需要通過equals方法來比較,由於ArrayList是泛型的,
所以其添加的元素,可能重載equals方法,自定義了判斷的原則。
3.grow方法中,對新容量大小進行判斷,為什么會定義MAX_ARRAY_SIZE的?
ArrayList底層存儲是使用數組來實現的,所以ArrayList存儲文件的大小必定受數組大小的限制,所以在擴容中,可以看到ArrayList對新容量大小進行邏輯判斷。
影響數組最大值:
-
理論上最大值為Integer.MAX_VALUE(2^32 - 1)
-
對象頭限制,不同類型的元素,可創建數組的最大值是不同的,byte是1字節,int是4字節
比如jvm可用內存為1M,32位機器下,
int[] bytes = new int[1024 * 1024 / 4]; byte[] bytes = new byte[1024 * 1024];
-
jvm可用內存大小限制
比如jvm可用內存為1M,32位機器下,
byte[] bytes = byte[1024 * 1024]
至於為什么MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
主要是在64為機器中,對象的
