JDK Vector源码学习

public class Vector<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

 

里面的方法 多为 synchronized  的因此Vector是线程安全的

 

Vector里面的好多api和 ArrayList是相似的

区别是线程安全与否 与  动态增长的时候的增长速率不同   动态增长会申请大的空间然后调用Arrays.copyOf()复制过去  这里又调用了System.arrayCopy() 这个是个native 方法

 

 

 

4个构造函数

 

public Vector() {
 this(10);
}

 

public Vector(int initialCapacity) {
 this(initialCapacity, 0);
}

 

public Vector(int initialCapacity, int capacityIncrement) {
       super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
      this.elementData = new Object[initialCapacity];
      this.capacityIncrement = capacityIncrement;
}


    protected int capacityIncrement; //与自动增长有关的一个量

 

public Vector(Collection<? extends E> c) {
     elementData = c.toArray();
     elementCount = elementData.length;
     // c.toArray might (incorrectly) not return Object[] (see 6260652)
     if (elementData.getClass() != Object[].class)
         elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}

 

与自动增长有关的方法

public synchronized void ensureCapacity(int minCapacity) {
     modCount++;
     ensureCapacityHelper(minCapacity);
}

 

private void ensureCapacityHelper(int minCapacity) {
 int oldCapacity = elementData.length;
 if (minCapacity > oldCapacity) {
     Object[] oldData = elementData;
     int newCapacity = (capacityIncrement > 0) ?            // vector 中的 capacityIncrement若是被设定了 就增长这么多
  (oldCapacity + capacityIncrement) : (oldCapacity * 2);   若是没有就增长2倍
         if (newCapacity < minCapacity) {
          newCapacity = minCapacity;
     }
            elementData = Arrays.copyOf(elementData, newCapacity);
   }
}

 

public synchronized void setSize(int newSize) {// 可能扩充 可能裁剪
    modCount++;
    if (newSize > elementCount) {
        ensureCapacityHelper(newSize);
    } else {
        for (int i = newSize ; i < elementCount ; i++) {
          elementData[i] = null;
       }
   }
   elementCount = newSize;

}

 

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

public synchronized int capacity() {   //返回可容纳的容量
 return elementData.length;
}

 

public synchronized int size() {  // 返回现有元素个数
 return elementCount;
}
 

你可能感兴趣的:(jdk,多线程,C++,c,C#)