天天看點

Vector底層結構和源碼分析

文章目錄

  • ​​1. Vector 的基本介紹​​
  • ​​2. 源碼分析​​
  • ​​3. Vector 和 ArrayList 的比較​​

1. Vector 的基本介紹

  1. Vector類的定義說明
  2. Vector底層結構和源碼分析
  3. Vector底層也是一個對象數組,​

    ​protected Object[] elementData;​

  4. Vector底層結構和源碼分析
  5. Vector是線程同步的,即線程安全,Vector類的操作方法帶有​

    ​synchronized​

public synchronized E get(int index) {
  if (index > = elementCount)
  throw new ArrayIndexOutOfBoundsException(index);
  return elementData(index);
}      
  • 在開發中,需要線程同步安全時,考慮使用Vector
  • 案例:

2. 源碼分析

  1. ​new Vector()​

    ​ 底層
public Vector() {
    this(10);
}      

補充:如果是 ​

​Vector vector = new Vector(8);​

​ 走的方法:

public Vector(int initialCapacity) {
this(initialCapacity, 0);
}      
  1. vector.add(i)

2.1 下面這個方法就添加資料到 vector 集合

public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}      

2.2 确定是否需要擴容 條件 : ​

​minCapacity - elementData.length>0​

private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0
  grow(minCapacity);
}      
//newCapacity = oldCapacity + ((capacityIncrement > 0) ?
//capacityIncrement : oldCapacity); 就是擴容兩倍. 
private void grow(int minCapacity) {
  // overflow-conscious code
  int oldCapacity = elementData.length;
  int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
  capacityIncrement : oldCapacity);
  if (newCapacity - minCapacity < 0)
  newCapacity = minCapacity;
  if (newCapacity - MAX_ARRAY_SIZE > 0)
  newCapacity = hugeCapacity(minCapacity);
  elementData = Arrays.copyOf(elementData, newCapacity);
}      

3. Vector 和 ArrayList 的比較