Vector
Vector源码分析
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { // 底层数组 protected Object[] elementData; // 相当于ArrayList的size属性 protected int elementCount; // 容量扩展增量 protected int capacityIncrement; private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; public synchronized int size() { return elementCount; } public Vector() { // 默认的容量大小是10 this(10); } public Vector(int initialCapacity) { // 默认的容量增量是0 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; } 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 boolean add(E e) { modCount++; // /ɪn'ʃʊə/ 确保 /kəˈpæsəti/ 容量 ensureCapacityHelper(elementCount + 1); // 把新元素添加到了末尾 elementData[elementCount++] = e; return true; } public synchronized boolean addAll(Collection<? extends E> c) { modCount++; Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); System.arraycopy(a, 0, elementData, elementCount, numNew); elementCount += numNew; return numNew != 0; } private void ensureCapacityHelper(int minCapacity) { // overflow-conscious code if (minCapacity - elementData.length > 0) // 扩展容量 grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // 如果不指定增量,扩展为原来的两倍 int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); if (newCapacity - minCapacity < 0) // 适用于addAll()方法 newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) /* private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; * 扩展至Integer的最大值 */ 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; } }