1. 程式人生 > >Vector原始碼學習

Vector原始碼學習

 

安全的可增長陣列結構


實現:
1. 內部採用陣列的方式。
  1.1 新增元素,會每次校驗容量是否滿足, 擴容規則有兩種,1.增加擴容補償的長度,2.按照現有陣列長度翻一倍。容量上限是Integer.MAX_VALUE。 copy使用Arrays.copy的api
  1.2 刪除元素
    1.2.1 通過物件刪除。遍歷陣列,刪除第一個匹配的物件
    1.2.3 通過下標刪除。判斷下標是否越界。
      使用 System.arraycopy進行copy, 並將元素的最後一位設定為null.供gc回收
2. 內部是同步[modCount]
  2.1 ArrayList資料結構變化的時候,都會將modCount++。
  2.2 採用Iterator遍歷的元素, next()會去檢查集合是否被修改[checkForComodification],如果集合變更會丟擲異常
  類似於資料庫層面的 樂觀鎖 機制。 可以通過 Iterator的api去刪除元素
3. 陣列結構,內部儲存資料是有序的,並且資料可以為null,支援新增重複資料
4. 執行緒安全的, 關於陣列的增刪方法都採用了synchronized標註。

 

原始碼學習

// 自動增長的物件陣列
public class Vector<E> {

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    // 元素陣列
    protected Object[] elementData;
    
    // 元素長度
    protected int elementCount;
    
    // 擴容步長[增長容量]
    protected int capacityIncrement;
    
    
// 集合變更次數 private int modCount = 0; public Vector(int initialCapacity) { this(initialCapacity, 0); // 10個長度,步長為0 } public Vector() { this(10); // 預設10個長度 } public Vector(int initialCapacity, int capacityIncrement) { super();
if (initialCapacity < 0) // 初始化容量 小於0 拋異常 throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; // 建立指定長度陣列 this.capacityIncrement = capacityIncrement; // 增長容量大小 } // 新增元素 public synchronized boolean add(E element) { modCount++; ensureCapacityHelper(elementCount + 1); // 校驗當前容器容量是否滿足 elementData[elementCount++] = element; return true; } public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; } private void ensureCapacityHelper(int minCapacity) { if (minCapacity - elementData.length > 0) // 當前下標 > 陣列長度 grow(minCapacity); }
   // 擴容方法
private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); // 如果步長大於0, 每次擴容步長大小,否則按陣列的長度翻一倍 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); 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; } public boolean remove(Object o) { return removeElement(o); } public synchronized E remove(int index) { modCount++; if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); int numMoved = elementCount - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--elementCount] = null; // Let gc do its work return oldValue; } // 從結尾開始查詢元素 public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); } // 指定位置,從結尾查詢元素 public synchronized int lastIndexOf(Object o, int index) { if (index >= elementCount) throw new IndexOutOfBoundsException(index + " >= "+ elementCount); if (o == null) { for (int i = index; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } private synchronized boolean removeElement(Object obj) { if (obj == null) { for (int index = 0; index < elementCount; index++) if (elementData[index] == null) { // 刪除 null fastRemove(index); return true; } } else { for (int index = 0; index < elementCount; index++) if (obj.equals(elementData[index])) { // eqals比較 fastRemove(index); return true; } } return false; } public synchronized void removeElementAt(int index) { modCount++; if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } else if (index < 0) { throw new ArrayIndexOutOfBoundsException(index); } int j = elementCount - index - 1; if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; elementData[elementCount] = null; /* to let gc do its work */ } private void fastRemove(int index) { modCount++; int numMoved = elementCount - index - 1; // 當前size - index - 1 陣列從0開始 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); // system arraycopy elementData[--elementCount] = null; // clear to let GC do its work gc回收 陣列最後一個元素設定為null } public synchronized Iterator<E> iterator() { return new Itr(); } 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() { // Racy but within spec, since modifications are checked // within or after synchronization in next/previous return cursor != elementCount; } public E next() { synchronized (Vector.this) { checkForComodification(); int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); cursor = i + 1; return elementData(lastRet = i); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.remove(lastRet); expectedModCount = modCount; } cursor = lastRet; lastRet = -1; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return elementData(index); } @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } public int size() { return elementCount; } }