1. 程式人生 > >你不知道的Java小知識——動態陣列實現(ArrayList原理)

你不知道的Java小知識——動態陣列實現(ArrayList原理)

你不知道的JAVA小知識——動態陣列實現(ArrayList原理)

什麼是陣列

  同類資料元素的集合,在計算機中以連續的地址儲存,編譯時確定長度,無法改變。

什麼是動態陣列

  資料結構中順序表的物理實現,同類資料元素的集合,在計算機中以連續的地址儲存,大小在建立時決定,但是可以改變。

為什麼使用動態陣列

  支援隨機訪問,查詢速度快。但是插入和刪除都需要移動元素,比起連結串列開銷較大。如:java集合類中的ArrayList Vector等

動態陣列實現程式碼(ArrayList原理)

/**
 * 順序表的實現
 * @author chengh
 * @param 
 */
public class ArrayList<E> { private Object[] data = null; // data: 用來儲存此線性表資料的陣列 private int capacity; // capacity: 線性表的容量 private int current; // current: 當前資料的下標 /** * 初始化為宣告大小,則設定為10。 */ ArrayList() { this(10); } /** * 初始化線性表,宣告儲存資料的陣列大小。 * @param
initialSize 順序表的初始化大小 */
ArrayList(int initialSize) { if (initialSize >= 0) { this.capacity = initialSize; data = new Object[initialSize]; current = 0; } else { throw new RuntimeException("初始化大小不能小於0:" + initialSize); } } /** * 線上性表的末尾新增元素,新增之前確認線性表是否已滿 * @param
e 待加入的元素 * @return */
public boolean AddElement(E e) { ensureCapacity(); data[current] = e; ++current; return true; } /** * 檢查儲存資料的陣列容量,如果陣列已經滿,則擴充容量;否則不操作。 */ private void ensureCapacity() { int index; if (current == capacity) { capacity *= 2; Object[] newData = new Object[capacity]; for(index = 0; index < current; ++index) { newData[index] = data[index]; } data = newData; } } /** * 返回下標為index的元素 * @param index 欲取得元素的下標 * @return */ public E get(int index) { validateIndex(index); return (E) data[index]; } /** * * @param index 待插入的位置 * @param e 待插入的元素 * @return */ public boolean set(int index, E e) { validateIndex(index); data[index] = e; return true; } /** * 驗證下標值是否合法,非法時丟擲異常 * @param index 待驗證的下標值 */ private void validateIndex(int index) { if (index < 0 || index > current) { throw new RuntimeException("無效的下標:" + index); } } /** * 返回當前順序表的大小 * @return */ public int size() { return current; } /** * 在指定位置插入指定元素 * @param index 待插入的位置 * @param e 待插入的元素 * @return */ public boolean insert(int index, E e) { validateIndex(index); ensureCapacity(); for (int temp = current; temp > index; --temp) { data[temp] = data[temp - 1]; } data[index] = e; return true; } /** * 刪除下標為index元素 * @param index 待刪除元素的下標 * @return */ public boolean delete(int index) { validateIndex(index); for ( ; index < current - 1; ++index) { data[index] = data[index + 1]; } data[current - 1] = null; --current; return true; } @Override public String toString() { String str = "[ "; for (Object o : data) { if (o != null) { str += o + " "; } } str += "]"; return str; } }