【Java集合类源码分析】Vector源码分析

【Java集合类源码分析】Vector源码分析

一、Vector简介

    Vector是JDK1.0引入的,基于动态数组实现的,其容量能够动态增长。

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

    Vector继承了AbstarctList抽象类,实现了List接口。
    Vector实现了RandomAccess接口,支持快速随机访问(通过下标序号进行快速访问);实现了Cloneable接口,支持克隆;实现了Serializable接口,支持序列化,能够通过序列化传输。
    Vector线程安全(实现方法加上了synchronized同步关键字),可在多线程环境下使用。

二、Vector源码分析

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * Vector基于该数组实现,用该数组存储元素
     * @serial
     */
    protected Object[] elementData;

    /**
     * 实际元素的个数
     * @serial
     */
    protected int elementCount;

    /**
     * 容量增长系数(当Vector的大小大于其容量时,其容量自动增加的量) 
     * 如果容量增量小于或等于零,则Vector每次需要增长时其容量将加倍
     * @serial
     */
    protected int capacityIncrement;

    /** 序列版本号 */
    private static final long serialVersionUID = -2767605614048989439L;

    /**
     * 构造具有指定的初始容量和容量增量的空Vector。
     * @param   initialCapacity     Vector的初始容量
     * @param   capacityIncrement   当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;
    }

    /**
     * 构造具有指定初始容量并且其容量增量等于0的空Vector
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * 构造一个空的Vector,使其内部的数据数组大小为10,其标准容量增量为0
     */
    public Vector() {
        this(10);
    }

    /**
     * 构造一个包含指定集合元素的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);
    }

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

    /**
     * 将当前容量值设为实际元素个数 
     * 如果该Vector的容量大于其当前大小,返回一个新数组给elementData,将容量更改为等于大小。 
     * 可以使用此操作来最小化向量容量以节省空间。
     */
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    /**
     * 如果需要,增加此向量的容量,以确保它可以至少容纳最小容量参数指定的元素数
     * @param minCapacity 所需的最小容量
     */
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    /**
     * 这实现了ensureCapacity的非同步语义。
     * 该类中的同步方法可以内部调用此方法来确保容量,而不会导致额外同步的成本。

     */
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        //当所需容量>Vector容量,进行扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 数组可被分配的最大容量。当需要的数组尺寸超过VM的限制时,可能导致OutOfMemoryError
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //当capacityIncrement>0,则容量增加capacityIncrement,否则,容量将增加一倍
        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的大小
     * @param  newSize  新大小
     */
    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > elementCount) {  //若新容量>当前Vector容量,则进行扩容
            ensureCapacityHelper(newSize);
        } else {  //若新容量<=当前Vector容量,则将newSize位置开始的元素都设置为null
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        elementCount = newSize;
    }

    /**
     * 返回此Vector当前的容量(即其内部数组的长度)
     */
    public synchronized int capacity() {
        return elementData.length;
    }

    /**
     * 返回此Vector实际大小(即Vector中元素个数)

     */
    public synchronized int size() {
        return elementCount;
    }

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

    /**
     * 返回Vector中全部元素对应的Enumeration
     */
    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");
            }
        };
    }

    /**
     * 如果此Vector中包含指定的元素,则返回true
     */
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    /**
     * 返回此Vector中指定元素第一次出现的索引(从前向后搜索)
     */
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    /**
     * 返回此Vector中指定元素第一次出现的索引
     * @param o 要查找的元素
     * @param index 从index位置开始从前向后查找
     */
    public synchronized int indexOf(Object o, int index) {
        if (o == null) {  说明Vector允许元素为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中指定元素最后一次出现的索引(从后向前搜索)
     */
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    /**
     * 返回此Vector中指定元素最后一次出现的索引
     * @param o 要查找的元素
     * @param index 从index位置开始从后向前查找
     */
    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);
    }

    /**
     * 返回此Vector的第一个元素(即索引0的元素)
     */
    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    /**
     * 返回此Vector的最后一个元素
     */
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

    /**
     * 将此Vector的指定索引处的元素设置为指定的对象
     */
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        elementData[index] = obj;
    }

    /**
     * 删除指定索引处的元素
     */
    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 */
    }

    /**
     * 在指定索引处插入元素 
     */
    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++;
    }

    /**
     * 将指定元素添加到此Vector的末尾,
     */
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    /**
     * 从此Vector中删除第一个出现的参数
     */
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    /**
     * 从此Vector中删除所有元素,并将其大小设置为零
     */
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    /**
     * 返回此Vector的克隆。 该副本将包含对内部数据数组的克隆的引用,而不是引用此Vector的原始内部数据数组(即浅拷贝)
     */
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
                Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    /**
     * 返回一个包含此Vector中所有元素的数组
     */
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    /**
     * 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型  
     */
    @SuppressWarnings("unchecked")
    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;
    }

    // 位置访问操作

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 返回此Vector中指定位置的元素
     */
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    /**
     * 用指定的元素替换此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;
    }

    /**
     * 将指定的元素追加到此Vector的末尾
     */
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

    /**
     * 删除此Vector中第一次出现的指定元素
     */
    public boolean remove(Object o) {
        return removeElement(o);
    }

    /**
     * 在此Vector中的指定位置插入指定的元素
     */
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    /**
     * 删除此Vector中指定位置的元素,并返回删除的元素
     */
    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;
    }

    /**
     * 从此Vector中删除所有元素 
     */
    public void clear() {
        removeAllElements();
    }

    // Bulk Operations

    /**
     * 如果此Vector包含指定集合中的所有元素,则返回true
     */
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    /**
     * 将指定集合中的所有元素追加到此Vector的末尾
     */
    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;
    }

    /**
     * 从此Vector中删除指定集合中包含的所有元素
     */
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    /**
     * 仅保留此向Vector中包含在指定集合中的元素
     */
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    /**
     * 将指定集合中的所有元素插入到此Vector中的指定位置
     */
    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;
    }

    /**
     * 将指定的对象与此向量进行比较以获得相等性
     */
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

    /**
     * 返回此Vector的哈希码值
     */
    public synchronized int hashCode() {
        return super.hashCode();
    }

    /**
     * 返回此Vector的字符串表示形式,其中包含每个元素的String表示
     */
    public synchronized String toString() {
        return super.toString();
    }

    /**
     * 获取此Vector中fromIndex(包括)到toIndex(不包括)的子集 
     */
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
    }

    /**
     * 删除此Vector中fromIndex到toIndex的元素
     */
    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实例的状态保存到流中(即序列化)
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }

}

三、Vector遍历方式

    1、通过迭代器Iterator遍历

Iterator iter = vector.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

    2、通过迭代器ListIterator遍历

ListIterator lIter = vector.listIterator();
//顺向遍历
while (lIter.hasNext()) {
    System.out.println(lIter.next());
}
//逆向遍历
while (lIter.hasPrevious()) {
    System.out.println(lIter.previous());
}

    3、随机访问,通过索引值遍历(由于实现了RandomAccess接口)

for (int i = 0; i < vector.size; i++) {
    System.out.println(vector.get(i));  
}

    4、foreach循环遍历

for (String str : vector) {
    System.out.println(str);  
}

    5、Enumeration遍历

Enumeration enu = vector.elements();
while (enu.hasMoreElements()) {
    System.out.println(enu.nextElement());
}

四、总结

    1、扩容机制:与ArrayList相同,Vector在每次增加元素时,都要调用ensureCapacityHelper()方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就先看构造方法中传入的容量增长量参数capacityIncrement是否为0,如果不为0,就设置新的容量为当前容量加上容量增长量,如果为0,就设置新的容量为旧的容量的2倍,如果设置后的新容量还不够,则直接将新容量设置为传入的参数(也就是所需的容量),而后同样用Arrays.copyof()方法将元素拷贝到新的数组
    2、几乎每个方法上都增加了synchronized 关键字来实现线程间的同步,来保证线程安全
    3、在查找给定元素索引值、删除指定元素等方法中,源码都将该元素的值分为null和不为null两种情况处理,Vector中允许元素为null
    4、Vector不仅支持Iterator和ListIterator迭代器遍历而且支持Enumeration遍历。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值