《Java源码分析》:Vector

《Java源码分析》:Vector

1、Vector的继承结构


    public class Vector<E>
        extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
 
 
  • 1
  • 2
  • 3
  • 4

从继承结构可以看出,Vector继承了AbstractList抽象类并实现了List、RandomAccess、Cloneable、Serializable接口,ArrayList的结构Vector一样。

RandomAccess接口是在源码中的注释如下:Marker interface used by List implementations to indicate that 
they support fast (generally constant time) random access.翻译下就是:这是一个标记性的接口,谁实现了这个接口就表明他具有快速随机访问的能力。

2、Vector的属性

elementData:数组,用来存放元素的

elementCount:记录数组中已经保存了的数据的个数

capacityIncrement:自动扩容的大小,即当数组满了之后,就添加capacityIncrement个空间装载元素,如果capacityIncrement<=0,则扩容时就扩容到目前Vector容量的两倍

    protected Object[] elementData;
    protected int elementCount;
    protected int capacityIncrement;

 
 
  • 1
  • 2
  • 3
  • 4

3、Vector构造函数

    /*
        其它的构造函数都是调用此构造函数
        参数的说明
        initialCapacity:指定的初始容量,默认值为10
        capacityIncrement:指定的每次的扩容大小,默认值是0,
                            capacityIncrement=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(int initialCapacity) {
        this(initialCapacity, 0);
    }

    public Vector() {
        this(10);
    }

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

当我们使用使用Vector时,如果我们知道Vector存储的元素大概会达到多少,就指定Vector的容量,当存储数量比较大时,就不要使用 Vector v= new Vector()来创建Vector实例对象,这个实际上就是创建了长度为10 ,增长因子为0 的Object 数组。当存储数量比较大时,会添加扩容后复制原来的数组中的元素到新数组中带来的开销。

Vector类中还有如下一个用Collection初始化Vector对象实例的构造函数

内部实现时直接将Collection转化为了数组返回。

    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);
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

add(E e)方法

添加元素的方法实现比较简单:直接在数组的后一个位置添加即可,不过在添加元素之前需要检查数组中是否已满,如果已满,则扩容。

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

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

扩容在Vector中是不可避免的,因此需要了解下ensureCapacityHelper函数

ensureCapacityHelper

这个函数,就是检查数组是否已满,如果已满,则调用grow函数进行扩容。扩容之后进行数据的拷贝即可。

其中,在grow函数中如果扩容后的数据进行一些判断,例如检测是否溢出呀,检测是否达到了MAX_ARRAY_SIZE呀,分别对这些进行了一些处理。

思路比较简单,因此源码也就比较容易看懂。

ArrayList类的扩容与这个一模一样。

源码如下:(添加了一些注释)

    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        //当数组已满,则调用grow函数来对数组进行扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //扩容的大小由capacityIncrement决定,如果capacityIncrement<=0,则扩容到目前数组的两倍
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        //检查是否newCapacity溢出了
        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;
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

add(int index, E element)

函数的功能:在指定位置添加元素

方法实现的思想也比较简单:首先检查是否需要扩容,如果需要,则进行扩容;接着将数组从索引index开始的元素全部向后移动一位。最后将元素保存在数组的index位置即可。

源码如下:(添加了一点注释)

    //在指定位置添加元素
    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++;
    } 

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

get(int index)方法

容器关键的两个方法分别为:添加元素、取出元素。因此,不可避免的我们需要分析下get方法的实现思路。

get方法就更简单了,由于Vector是借助于数组来实现的,因此get方法的内部实现也就是取出位置为index的元素。


    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

上面的get、add方法都是用了synchronized关键字进行修饰,说明他们是线程安全的,在多线程并发时,不需要我们进行额外的同步。而ArrayList是没有进行同步的。这也是Vector和ArrayList的一个区别

set(int index, E element)方法

既然我们知道Vector底层是基于数组来实现的,则set方法我们用屁股都想得到是怎么实现的,比较简单哈。


    public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

remove(Object o)方法

函数的功能:去除掉元素o。

思路:先找到该元素在数组中的位置index;然后移除索引位置为index的元素即可

思路清晰之后,源码也就比较好理解了。

源码如下:(添加了一些注释)

    /*
        函数的功能:去除掉元素o。
        思路:先找到该元素在数组中的位置index;然后移除索引位置为index的元素即可
    */
    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 int indexOf(Object o) {
        return indexOf(o, 0);
    }
    /*
        函数的功能:找到元素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;
    }
    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 */
    }

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

上面的去除掉元素,Vector还提供了remove另外一种形式,

remove(int index)

函数功能:去除掉Vector索引为index位置的元素。

这个源码的实现也比较简单,源码如下:

    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;
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

elements方法

方法中创建了一个枚举类型,里面实现还是通过元素是否存在,通过下标遍历数组,这里就过多的进行介绍。

    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");
            }
        };
    }

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

小结

Vector里面还有很多方法,我们只需要知道Vector里面是基于数组来实现的,然后用正常的思维来思考常见的方法的实现也没有任何问题的,这里就不做过多的介绍了。需要注意的是:Vector是线程安全的,因此,在多线程并发中是不需要使用额外同步的,而ArrayList实现基本与Vector一样,但是区别是:ArrayList是线程不安全的,在多线程并发时,需要我们进行额外的同步

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值