深入学习Java之Vector

深入学习Java之Vector

前言

在前面我们学习了关于List接口中的几个实现ArrayListLinkedList以及Queue接口的实现ProrityQueue、接下来我们来学习另外一个比较常用的List接口的实现VectorVector属于元老级别的容器了,从JDK1.0就已经存在了,实现基本上跟ArrayList是类似的,只不过由于Vector加多了一些同步机制,保证Vector是线程安全的(还记得吗,之前学过的那几个容器都是非线程安全的)

Vector的继承结构

首先先来看下Vector的继承结构
Vector继承结构

从上图中可以看到,Vector所继承或者实现的类/接口都是之前所接触过的,言下之意,除非Vector自身新增了一些方法,否则,Vector的操作方式是跟ArrayList的操作是基本相同的,由于我们在前面的内容中已经学习过了上面所涉及到的相关接口,这里就不再重复了,如果还不是很熟悉的话,可以翻阅前面的内容进行学习

Vector源码剖析

接下来我们来深入学习Vector的源码

Vector的组成

    // 内部实现为Object数组
    protected Object[] elementData;
    // 实际元素的数量
    protected int elementCount;

构造方法


    // 指定容量以及指定扩容时的增长量
    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<? extends E> c) {
        // 直接将容器转为数组,并且指向该数组
        elementData = c.toArray();
        elementCount = elementData.length;
        // 如果容器中元素的类型不是Object,则进行转换
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

插入元素


    // 需要注意的是,这里的操作使用了synchronized修饰
    public synchronized boolean add(E e) {
        modCount++;
        // 确保容量
        ensureCapacityHelper(elementCount + 1);
        // 默认插入在最后面
        elementData[elementCount++] = e;
        return true;
    }

    // 默认在最后插入元素
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    // 在指定位置插入元素
    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                                                     + " > " + elementCount);
        }
        ensureCapacityHelper(elementCount + 1);
        // 将数组中index后面的内容后移
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }

    // 在指定位置插入元素,这里可以看到,底层是使用insertElementAt方法
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    // 将容器的内容插入到Vector中,默认是插入在后面
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);
        // 直接将a的内容拷贝到elementData后面
        System.arraycopy(a, 0, elementData, elementCount, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

    // 在指定位置加入容器中的所有元素
    public synchronized boolean addAll(int index, Collection<? extends E> 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;

        // 如果需要移动的元素大于0,也就是
        // 插入的位置不是在当前Vector的最后面,则将index之后的
        // 元素先后移
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        // 将新的元素拷贝至当前数组
        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

确保容量以及动态增长


    // 确保容量
    private void ensureCapacityHelper(int minCapacity) {
        // 如果所需要的最小容量大于当前数组的长度,则进行扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    // 动态增长
    private void grow(int minCapacity) {

        int oldCapacity = elementData.length;
        // 如果构造Vector的时候,有传入增长的数量,则使用该数组
        // 否则,默认的增长为原来容量的一倍
        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) {
        // 如果此时的容量小于0,说明出现了溢出,从上面的内容可以
        // 知道,minCapacity = elementCount + 新加入的数据的长度
        // 此时有可能会导致整数溢出,所以需要进行特殊判断
        if (minCapacity < 0) 
            throw new OutOfMemoryError();
        // 如果所申请的内存大于允许的最大值,则使用Integer.MAX_VALUE
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

获取元素


    // 获取第一个元素
    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    // 获取最后一个元素
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

    // 指定位置的元素
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);
    }

    // 获取指定位置的元素
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    // 返回元素,这里直接将Object类型转化为泛型所指定的类型
    E elementData(int index) {
        return (E) elementData[index];
    }

获取元素的索引


    // 查找指定元素的索引
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    // 从指定位置开始,查找指定元素的索引
    public synchronized int indexOf(Object o, int index) {
        // 如果元素是null,则返回第一个null元素的索引
        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;
        }
        // 如果找不到,则返回-1
        return -1;
    }

    // 从后往前查找第一个匹配元素的索引
    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;
    }

修改元素


    // 将指定位置的元素的值设置为新的值
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        elementData[index] = obj;
    }

    // 替换指定位置的元素值,并且返回旧值
    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 E remove(int index) {
        modCount++;
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);

        int numMoved = elementCount - index - 1;
        // 如果需要移动的元素数量大于0,也就是删除的元素不是最后一个元素
        // 则将后面的元素前移
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 将最后面的元素(此时所有的元素已经前移了一个位置)指向null
        // 辅助垃圾回收机制进行垃圾回收
        elementData[--elementCount] = null;

        return oldValue;
    }

    // 删除第一个匹配的元素
    public boolean remove(Object o) {
        return removeElement(o);
    }

    // 删除指定元素
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        // 查找第一个找到的元素
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            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 */
    }

    // 删除指定范围的元素
    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;
    }

    // 删除所有元素
    public synchronized void removeAllElements() {
        modCount++;
        // 所有元素指向null,方便垃圾回收器进行垃圾回收
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    // 删除容量中包含的元素
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    // 删除不包含在容器中的元素
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    // 清除容器中的元素
    public void clear() {
        removeAllElements();
    }

其他常用操作


    // 查看是否包含容器中的所有元素
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    // 将Vector转成array
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    // 将Vector转成array
    public synchronized <T> T[] toArray(T[] a) {
        if (a.length < elementCount)
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());

        System.arraycopy(elementData, 0, a, 0, elementCount);

        if (a.length > elementCount)
            a[elementCount] = null;

        return a;
    }

    // 查看是否包含某个元素
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    // 返回枚举对象
    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;

            public boolean hasMoreElements() {
                return count < elementCount;
            }

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

    // 判断是否为空
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

    // 查看元素个数
    public synchronized int size() {
        return elementCount;
    }

    // 查看容量
    public synchronized int capacity() {
        return elementData.length;
    }

    // 手动调整数组的大小,如果指定的容量比当前容量小
    // 会删除后面的元素
    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 void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    // 将数组的元素拷贝至指定的数组中
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

总结

本小节主要学习了Vector,从上面的代码分析中可以看到,Vector的基本操作和实现都是与ArrayList类似的,不过ArrayList是非线程安全的,而Vector是线程安全的,言下之意,当在多线程环境下使用List容器时,Vector是比较好的选择,不过,由于进行同步等的操作,Vector的效率理论上会比其他几个List的操作低一些,而在非多线程的环境下,则可以根据需要选择ArrayList或者LinkedList,以便达到更高的效率

猜你喜欢

转载自blog.csdn.net/xuhuanfeng232/article/details/77108763