原始碼分析之手寫ArrayList
阿新 • • 發佈:2018-12-06
public class ExtArrayList { // 底層採用陣列存放 private Object[] elementData; // 陣列預設容量 private static final int DEFAULT_CAPACITY = 10; // 實際arraylist長度 private int size; // 陣列初始容量 public ExtArrayList(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } elementData = new Object[initialCapacity]; } // 預設陣列的容量 public ExtArrayList() { this(DEFAULT_CAPACITY); } // 執行緒安全 public void add(Object object) { ensureExplicitCapacity(size + 1); elementData[size++] = object; /*// 1.判斷實際存放的容量是否大於elementData if (size == elementData.length) { // 新陣列的容量大小 int newCapacity = 2 * size; * Object[] newObjects = new Object[newCapacity]; for (int i = 0; i * < elementData.length; i++) { newObjects[i] = elementData[i]; } elementData = Arrays.copyOf(elementData, newCapacity); } // 2.使用下表賦值 elementData[size++] = object;*/ } public void add(int index, Object object) { get(index); ensureExplicitCapacity(size + 1); System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = object; size++; } public void ensureExplicitCapacity(int minCapacity) { // 如果存入的資料,超出了預設陣列初始容量 就開始實現擴容 if (size == elementData.length) { // 獲取原來陣列的長度 2 int oldCapacity = elementData.length; // oldCapacity >> 1 理解成 oldCapacity/2 新陣列的長度是原來長度1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); // 3 if (newCapacity < minCapacity) { // 最小容量比新容量要小的,則採用初始容量minCapacity newCapacity = minCapacity; } // System.out.println("oldCapacity:" + oldCapacity + ",newCapacity:" // + newCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } } // 使用下表獲取陣列元素 public Object get(int index) { return elementData[index]; } // 刪除元素 下標 public Object remove(int index) { // 查詢元素 get(index); // 刪除原理分析 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 return null; } //刪除元素 物件 public boolean remove(Object obj){ for (int i = 0; i < elementData.length; i++) { Object value=elementData[i]; if(value.equals(obj)){ remove(i); return true; } } return false; } public int getSize() { return size; } }