Vector 源码分析

这篇文章来自我的博客

正文之前

之前介绍过 ArrayListLinkedList,所以今天来说说 List 接口的另一个实现类:Vector,其实这也是一个类似的动态数组,只不过是线程安全的,和 ArrayList 还是有一点区别的

主要内容:

  1. 基本概念
  2. 构造
  3. 针对容量的操作
  4. 增删改查

正文

1. 基本概念

关于 Vector 的介绍,其实直接看 JDK 中的注释就解释的很清楚了:

/**
 * The {@code Vector} class implements a growable array of
 * objects. Like an array, it contains components that can be
 * accessed using an integer index. However, the size of a
 * {@code Vector} can grow or shrink as needed to accommodate
 * adding and removing items after the {@code Vector} has been created.
 *
 * <p>Each vector tries to optimize storage management by maintaining a
 * {@code capacity} and a {@code capacityIncrement}. The
 * {@code capacity} is always at least as large as the vector
 * size; it is usually larger because as components are added to the
 * vector, the vector's storage increases in chunks the size of
 * {@code capacityIncrement}. An application can increase the
 * capacity of a vector before inserting a large number of
 * components; this reduces the amount of incremental reallocation.
 */
复制代码

首先,Vector 是一个可增长的数组(和 ArrayList 类似),能够用索引直接找到元素,Vector 的容量可增可减

其次,Vector 使用变量 capacitycapacityIncrement 来进行容量的管理,关于容量和大小的说法,之前也提到过,容量是最多能够容纳多少元素,而大小是目前容纳了多少元素。capacity 指的就是容量,是永远大于或等于 Vector 的大小的,不过容量通常是大于 Vector 的大小的,因为它扩容的方式有点特殊,下文提及,在插入大量数据之前,最好能进行适当的扩容,避免了再分配的时间浪费

Vector 是线程安全的,它所有的方法都加上了 synchronized 关键字

关于 Vector,需要先介绍一下它的变量:

    // Vector 的操作就是基于这个数组来实现的:
    protected Object[] elementData;
    
    // Vector 中的元素数量
    protected int elementCount;

    // Vector 的增量,用它来判断需要扩容多少
    protected int capacityIncrement;

    //某些 JVM 会在数组的前几位保留一些信息(具体的也不晓得)
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
复制代码
2. 构造

关于 Vector 的构造器,有四种方式:

1. 使用给定的初始容量和增量来创造一个空的 Vector
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            //容量为负
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        //根据容量创造数组
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }
复制代码
2. 使用给定的容量来创造一个空的 Vector

调用了上一个构造器

    //增量设置为0
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }
复制代码
3. 不带参数创造一个空的 Vector

调用上一个构造器,并将容量初始值设为10

    public Vector() {
        this(10);
    }
复制代码
4. 创造一个带有其他容器元素的 Vector
    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);
    }
复制代码
3. 针对容量的操作
1. 增长容量

增长容量的操作真是一套又一套,和俄罗斯套娃一样,用一个同步的公有方法来调用其他未同步的私有方法:

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

    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;
        //如果增量大于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;
    }
复制代码
2. 缩减容量

有时候,使用 Vector 完成任务之后,容量会有剩余,可以调用这个方法把容量调整至与大小相同:

    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        //如果容量多余
        if (elementCount < oldCapacity) {
            //原地复制
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }
复制代码
3. 设置大小

根据给定的大小设置 Vector,如果 newSize 小于 Vector 的 size,则抹掉后面的部分

    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;
    }
复制代码
4. 得到容量或大小的数值

很简单,直接上代码:

    public synchronized int capacity() {
        return elementData.length;
    }

    public synchronized int size() {
        return elementCount;
    }
复制代码
5. 判断是否为空
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }
复制代码
4. 增删改查
1. 增
  • 先扩容,再添加:
    public synchronized boolean add(E e) {
        modCount++;
        //先扩容
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
复制代码
  • 在指定位置添加:
    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 void add(int index, E element) {
        insertElementAt(element, index);
    }
复制代码
  • 在末尾添加:
    public synchronized void addElement(E obj) {
        modCount++;
        //扩容后在末尾添加
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }
复制代码
  • 在末尾添加指定集合的元素:
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        //转为数组后根据大小进行扩容
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);
        //将数组内容复制到 Vector 的末尾
        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;
        //先将元素后移,空出位置之后,在将指定容器的元素加入
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;
        return numNew != 0;
    }
复制代码
2. 删
  • 删除指定位置的元素(无返回值)
    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);
        }
        //元素前移,大小减1,并将最后一个位置设为 null,让 GC 进行处理
        elementCount--;
        elementData[elementCount] = null; /* to let gc do its work */
    }
复制代码
  • 删除指定位置的元素(有返回值)

过程和上面的是类似的,区别就是这个方法返回删除的元素

    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 synchronized boolean removeElement(Object obj) {
        modCount++;
        //查找该元素位置
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    //这也是一样的
    public boolean remove(Object o) {
        return removeElement(o);
    }
复制代码
  • 删除全部元素
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            //把每个位置都设为空就行了
            elementData[i] = null;

        elementCount = 0;
    }

    //清空列表,效果是一样的
    public void clear() {
        removeAllElements();
    }
复制代码
3. 改
  • 修改指定位置的元素
    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;
    }
复制代码
4. 查

Vector 中查找的方式比较多,下面一一列举:

  • 枚举出所有元素
    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 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;
    }
复制代码
  • 查找指定元素或判断是否包含指定元素:
    //从0开始查找
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    //也是从0开始,返回布尔类型
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }
复制代码
  • 查找指定元素最后一次出现的位置

其实就是把上面查找的方式倒过来,不解释:

    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 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);
    }
复制代码
  • 查找首尾元素:
    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);
    }
复制代码
4. 总结

之前在学习 Java 的时候,没有听到过 Vector 的相关概念,还是在学习 ArrayList 的时候,发现挺多人拿 ArrayList 和 Vector 来作比较,后来才知道,Vector 其实可以算得上是线程安全的 ArrayList

首先,他们继承的类和实现的接口是一样的,说明他们能够实现相同的功能:

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

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

复制代码

其次,在上述的操作中可以看出,它和 ArrayList 的操作还是很类似的

Vector 是从 JDK1.0 出现的,而 ArrayList 是从 JDK1.2 出现的,从网上的一些其他人的观点中可以看出,Vector 似乎没什么存在感了,ArrayList 也可以通过集合的包装来实现线程安全的效果,不过这不应该成为我们不学习的理由,谁知道哪一天就派上用场了呢

关于 Vector 的迭代器操作,粗略看了一下,与 ArrayList 的极其相似,甚至有一些操作就是 ArrayList 的操作,所以就不必用多篇文章来阐述,接下来会是集合类中的其他 API

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值