Java 集合深入理解:Vector

都说Vector和ArrayList相同,只不过Vector是同步的,看下源码

Vector继承结构

public class Vector
    extends AbstractList
    implements List, RandomAccess, Cloneable, java.io.Serializable
{...}

Vector 和 ArrayList 一样,都是继承自 AbstractList。它是 Stack 的父类。

成员变量

底层实现是数组

protected Object[] elementData;

数组元素个数

protected int elementCount;

扩容时增长数量

protected int capacityIncrement;

Vector 的 4 种构造方法

//创建指定容量大小的数组,设置增长量。如果增长量为 非正数,扩容时会扩大两倍
public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}
//创建一个用户指定容量的数组,同时增长量为 0 
public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}
//创建默认容量 10 的数组
public Vector() {
    this(10);
}

//创建一个包含指定集合的数组
public Vector(Collection 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);
}

Vector 的成员方法

//扩容,传入最小容量,跟 ArrayList.grow(int) 很相似,只是扩大量不同 
private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    //如果增长量 capacityIncrement 不大于 0 ,就扩容 2 倍
    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);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

Vector中的 5 种添加元素的方法

//尾部插入元素,同步的
public synchronized void addElement(E obj) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = obj;
}

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

private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

public void add(int index, E element) {
    insertElementAt(element, index);
}
//在指定位置插入一个元素,同步的
public synchronized void insertElementAt(E obj, int index) {
    modCount++;
    if (index > elementCount) {
        throw new ArrayIndexOutOfBoundsException(index
                                                 + " > " + elementCount);
    }
    ensureCapacityHelper(elementCount + 1);
    System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    elementData[index] = obj;
    elementCount++;
}
//添加一个集合到尾部,同步的
public synchronized boolean addAll(Collection 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;
}
//添加一个结合到指定位置,同步的
public synchronized boolean addAll(int index, Collection c) {
    modCount++;
    if (index < 0 || index > elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityHelper(elementCount + numNew);

    int numMoved = elementCount - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                         numMoved);

    System.arraycopy(a, 0, elementData, index, numNew);
    elementCount += numNew;
    return numNew != 0;
}

Vector 中的删除方法(有些没贴)

public synchronized boolean removeElement(Object obj) {
    modCount++;
    int i = indexOf(obj);
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

public synchronized void removeAllElements() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}

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 void clear() {
    removeAllElements();
}

public synchronized boolean removeAll(Collection c) {
    return super.removeAll(c);
}

protected synchronized void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = elementCount - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
                     numMoved);

    // Let gc do its work
    int newElementCount = elementCount - (toIndex-fromIndex);
    while (elementCount != newElementCount)
        elementData[--elementCount] = null;
}

Vector 中的修改方法

//修改指定位置为指定元素
public synchronized E set(int index, E element) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    //找到这个元素,直接设置新值
    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

//修改指定位置为指定元素
public synchronized void setElementAt(E obj, int index) {
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    //数组就是方便,直接更新就好了
    elementData[index] = obj;
}

Vector 中的查询

//查找 o 从指定位置 index 开始第一次出现的位置
public synchronized int indexOf(Object o, int index) {
    if (o == null) {
        for (int i = index ; i < elementCount ; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = index ; i < elementCount ; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

总结

Vector 特点

  1. 底层由一个可以增长的数组组成
  2. Vector 通过 capacity (容量) 和 capacityIncrement (增长数量) 来尽量少的占用空间
  3. 扩容时默认扩大两倍
  4. 最好在插入大量元素前增加 vector 容量,那样可以减少重新申请内存的次数
  5. 通过 iterator 和 lastIterator 获得的迭代器是 fail-fast 的
  6. 通过 elements 获得的老版迭代器 Enumeration 不是 fail-fast 的
  7. 同步类,每个方法前都有同步锁 synchronized
  8. 在 JDK 2.0 以后,经过优化,Vector 也加入了 Java 集合框架大家族

Vector与ArrayList

共同点:

  • 底层实现都是数组
  • 都可以扩容
  • 实现了RandomAccess 所以都支持随机访问

不同点:

  • Vector线程安全,ArrayList线程非安全
  • Vector 比 ArrayList 多一种迭代器 Enumeration
  • Vector 默认扩容 2 倍,ArrayList 是 1.5

不考虑线程安全方面一般推荐使用 ArrayList,因为每次都要获取锁,效率太低。

你可能感兴趣的:(Java 集合深入理解:Vector)