標籤:刪除 def rem rac with 介面 是的 大小 ali
下面我們來看看ArrayList的底層實現,
ArrayList繼承了AbstractList,實現Cloneable、Serializable、RandomAccess介面,
它的成員屬性有Object[] elementData 和 int size,
顯然底層是以可擴充的數組來儲存元素,
新增元素
有如下這段代碼,
public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1);}
我們進到add(E e)方法,下,
1 public boolean add(E e) {2 ensureCapacityInternal(size + 1); // Increments modCount!!3 elementData[size++] = e;4 return true;5 }
size因為是成員屬性,並且是基礎資料型別 (Elementary Data Type),所以它的初始值為0,
第3行elementData[size++] = e;等價於第一步先elementData[0] = e ,第二步size自增,
第2行的 ensureCapacityInternal(size + 1),上面我們也提到了,Object[] elementData是一個可動態擴充的一個數組,
因此我們需要校正當前的的容量是否滿足元素的儲存,如果不滿足,又是採取怎樣的方式進行擴容呢?
我們來看 ensureCapacityInternal(int minCapacity),
1 private void ensureCapacityInternal(int minCapacity) {2 if (elementData == EMPTY_ELEMENTDATA) {3 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);4 }5 6 ensureExplicitCapacity(minCapacity);7 }
DEFAULT_CAPACITY = 10 是預設的數組容量,
下面來看ensureExplicitCapacity(int minCapacity),
1 private void ensureExplicitCapacity(int minCapacity) {2 modCount++;3 4 // overflow-conscious code5 if (minCapacity - elementData.length > 0)6 grow(minCapacity);7 }
如果需要的長度大於數組當前的長度,則調用grow(int minCapacity),
1 private void grow(int minCapacity) { 2 // overflow-conscious code 3 int oldCapacity = elementData.length; 4 int newCapacity = oldCapacity + (oldCapacity >> 1); 5 if (newCapacity - minCapacity < 0) 6 newCapacity = minCapacity; 7 if (newCapacity - MAX_ARRAY_SIZE > 0) 8 newCapacity = hugeCapacity(minCapacity); 9 // minCapacity is usually close to size, so this is a win:10 elementData = Arrays.copyOf(elementData, newCapacity);11 }
擴容的規則是,當前數組的長度乘以1.5,結果帶小數則取整數,
最後調用Arrays.copyOf(T[] original, int newLength),直接看到最內層的實現,
1 public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {2 T[] copy = ((Object)newType == (Object)Object[].class)3 ? (T[]) new Object[newLength]4 : (T[]) Array.newInstance(newType.getComponentType(), newLength);5 System.arraycopy(original, 0, copy, 0,6 Math.min(original.length, newLength));7 return copy;8 }
會建立一個新數組,同時將原數組的內容複寫到新數組中,
擴容是的操作是int newCapacity = oldCapacity + (oldCapacity >> 1),我們可以這麼認為
1.擴容一次性太多,勢必會造成對記憶體空間的過多佔用,
2.擴容太少,會造成次數太多,下次的擴容很快到來,同時,將原數組的元素複製到新的數組中,頻繁的數組拷貝需要消耗一定的效能,
因此也許這是一種比較折中的處理方式,
刪除元素
如下一段代碼
1 public static void main(String[] args) {2 List<Integer> list = new ArrayList<Integer>();3 list.add(111);4 list.add(222);5 list.remove(1);6 list.remove(222);7 }
元素的刪除分為兩種,一種是按照下標來刪除,一種是按照元素來刪除
按照下標來刪除元素,先看一下代碼,
1 public E remove(int index) { 2 rangeCheck(index); 3 4 modCount++; 5 E oldValue = elementData(index); 6 7 int numMoved = size - index - 1; 8 if (numMoved > 0) 9 System.arraycopy(elementData, index+1, elementData, index,10 numMoved);11 elementData[--size] = null; // clear to let GC do its work12 13 return oldValue;14 }
第二行,校正是否越界,第九行將刪除的資料之後的元素往前移動一位,第十一行將size自減,同時將最後一位引用指向null
clear to let GC do its work!
按照元素來刪除元素,先看一下代碼,
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;}
遍曆找出下標之後調用 fastRemove(int index),代碼如下,
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}
兩種實現方式差不多,最後都是調用上面的數組部分元素的移動,以及最後一位引用讓虛擬機器自己釋放元素的引用
插入元素
如下一段代碼,
1 public static void main(String[] args) {2 List<Integer> list = new ArrayList<Integer>();3 list.add(111);4 list.add(222);5 list.add(1,22222);6 }
第5行表示,在第一個元素之後插入22222,
我們進到add(int index, E element),
1 public void add(int index, E element) {2 rangeCheckForAdd(index);3 4 ensureCapacityInternal(size + 1); // Increments modCount!!5 System.arraycopy(elementData, index, elementData, index + 1,6 size - index);7 elementData[index] = element;8 size++;9 }
第2行,校正插入的位置是否在數組的大小範圍內,否則跑出異常,
第4行,判斷是否有必要擴容,和新增元素的擴容是一樣方法,
第5行,插入的位置到最後的所有元素向後移動一位,
第6行,插入的位置的引用指向新元素,
下面我們ArrayList實現了Random介面,然鵝RandomAccess是一個空介面,javadoc中是這麼描述的,
Marker interface used by <tt>List</tt> implementations to indicate thatthey support fast (generally constant time) random access.
翻譯過來的意思是 這是一個標記介面,僅僅是一個標記,arrayList實現標記,表明它能快速的查詢資料,
從上面幾個方面,我們總結一下ArrayList的優缺點,
優點
1.新增一個元素,順序新增,增加數組元素的一個引用而已,
2.數組查詢非常快捷,
缺點
1.刪除元素,會造成部分元素的移動,勢必會造成效能的一定影響,
2.插入元素,會造成部分元素的移動,勢必會造成效能的一定影響,
所以,在業務開發中,涉及到查詢較多的,考慮ArrayList。
同樣,想借鑒大神對於集合的四個關注點
1.是否允許為空白,
2.元素是否允許重複,
3.元素的儲存順序與尋找順序是否一致,
4.是否安全執行緒,
ArrayList允許元素為空白,允許重複,有序,非安全執行緒,
我們再回頭看數組的定義
private transient Object[] elementData;
被transient關鍵字修飾,表示該數組不會被序列化,而是提供了writeObject(java.io.ObjectOutputStream s),javadoc有這麼一句話,
Save the state of the <tt>ArrayList</tt> instance to a stream (thatis, serialize it)
我們來看一下writeObject(java.io.ObjectOutputStream s),
1 private void writeObject(java.io.ObjectOutputStream s) 2 throws java.io.IOException{ 3 // Write out element count, and any hidden stuff 4 int expectedModCount = modCount; 5 s.defaultWriteObject(); 6 7 // Write out size as capacity for behavioural compatibility with clone() 8 s.writeInt(size); 9 10 // Write out all elements in the proper order.11 for (int i=0; i<size; i++) {12 s.writeObject(elementData[i]);13 }14 15 if (modCount != expectedModCount) {16 throw new ConcurrentModificationException();17 }18 }
第5行,對非transient的成員屬性序列化,
第11~13行,對有數組中有值得元素逐個序列化。
這麼做的好處,
1.大大縮短序列化的時間,
2.減少序列化後檔案的大小。
Java集合之ArrayList源碼解析