JDK源码深入学习之Vector

Vector概述

1.Vector是一个矢量队列,底层基于数组实现
2.Vector继承于AbstractList,实现了List, RandomAccess, Cloneable这些接口
3.Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。
4.Vector里面的元素都是有序可重复的
5.Vector 是线程安全的,但也导致了性能要低于ArrayList

由于Vector与ArrayList极其的相似,这里做一个对比ArrayList源码解读
相同点
1.底层都是数组
2.增删查的操作基本类似
3.初始长度都为10
4.继承类和实现的接口相同
不同点
1.Vector中方法都加了synchronized关键字保证线程安全,ArralList线程不安全
2.Vector新增capacityIncrement容量增长因子参数,用于扩容机制。capacityIncrement>0,扩容至(原数组size+capacityIncrement)大小
3.Vector扩容机制增长1倍(capacityIncrement==0),ArrayList扩容1.5倍
4.Vector变量用protected修饰,ArrayList用的private修饰
Vector类图:
在这里插入图片描述

Vector源码解读

1.Vector定义(与ArrayList一样)

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

2.Vector定义的变量

    // Vector实际存放数据的数组
    protected Object[] elementData;

    // 数组大小
    protected int elementCount;

    // 容量增长系数
    protected int capacityIncrement;

3.Vector构造器
(1)指定初始化数组大小和容量增长系数的构造器

    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)指定初始化数组大小和容量增长系数为0的构造器

    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

(3)指定默认构造数组大小为10,容量增长系数为0的构造器

    public Vector() {
        this(10);
    }

(4)指定集合的构造器

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

4.添加一个元素add()方法

    // 添加一个元素
    public synchronized boolean add(E e) {
        // 操作计数+1
        modCount++;

        // 判断是否扩容,需扩容则扩容
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
    
    // 判断是否扩容,需扩容则扩容
    private void ensureCapacityHelper(int minCapacity) {
        if (minCapacity - elementData.length > 0)
            // 扩容
            grow(minCapacity);
    }
    
    //扩容
    private void grow(int minCapacity) {
        // 原数组大小
        int oldCapacity = elementData.length;
        /* 新数组大小
        当Vector的容量不足以容纳当前的全部元素,增加容量大小。
        若容量增长因子capacityIncrement > 0,数组扩容增加capacityIncrement个长度
        若容量增长因子capacityIncrement <= 0,数组扩容增加1倍
         */
        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);
    }

5.删除一个元素方法remove()
JDK提供2个remove移除方法,分别是根据元素移除和根据下标移除。
根据元素移除元素:

    // 移除某个元素
    public boolean remove(Object o) {
        return removeElement(o);
    }

    public synchronized boolean removeElement(Object obj) {
        // 操作计数+1
        modCount++;
        // 取得移除元素的下标位置
        int i = indexOf(obj);
        if (i >= 0) {
            // 根据下标位置移除元素
            removeElementAt(i);
            return true;
        }
        return false;
    }

    public synchronized void removeElementAt(int index) {
        // 操作计数+1
        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
        elementCount--;
        // 清空原数组最后一个位置元素为null
        elementData[elementCount] = null; /* to let gc do its work */
    }


根据下标移除元素:

    // 根据下标移除某个元素
    public synchronized E remove(int index) {
        // 操作计数+1
        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);
        
        // 清除最后一个元素赋值为null,数组大小-1
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }

    // 根据下标取得元素
    E elementData(int index) {
        return (E) elementData[index];
    }

6.取得一个元素get()

    // 根据下标取得元素
    E elementData(int index) {
        return (E) elementData[index];
    }

Vector遍历方式

1.迭代器

 Iterator iterator = vector.iterator();
        while (iterator.hasNext()){
            iterator.next();
}

2.随机访问

Integer value = null;
int size = vector.size();
for (int i=0; i<size; i++) {
    value = (Integer)vector.get(i);        
}

3.java 8新特性

vector.forEach(a -> {});

4.foreach循环

Integer value = null;
for (Integer integ:vec) {
    value = integ;
}

5.Enumeration遍历

Integer value = null;
Enumeration enu = vec.elements();
while (enu.hasMoreElements()) {
    value = (Integer)enu.nextElement();
}

Vector所有API

synchronized boolean        add(E object)
             void           add(int location, E object)
synchronized boolean        addAll(Collection<? extends E> collection)
synchronized boolean        addAll(int location, Collection<? extends E> collection)
synchronized void           addElement(E object)
synchronized int            capacity()
             void           clear()
synchronized Object         clone()
             boolean        contains(Object object)
synchronized boolean        containsAll(Collection<?> collection)
synchronized void           copyInto(Object[] elements)
synchronized E              elementAt(int location)
             Enumeration<E> elements()
synchronized void           ensureCapacity(int minimumCapacity)
synchronized boolean        equals(Object object)
synchronized E              firstElement()
             E              get(int location)
synchronized int            hashCode()
synchronized int            indexOf(Object object, int location)
             int            indexOf(Object object)
synchronized void           insertElementAt(E object, int location)
synchronized boolean        isEmpty()
synchronized E              lastElement()
synchronized int            lastIndexOf(Object object, int location)
synchronized int            lastIndexOf(Object object)
synchronized E              remove(int location)
             boolean        remove(Object object)
synchronized boolean        removeAll(Collection<?> collection)
synchronized void           removeAllElements()
synchronized boolean        removeElement(Object object)
synchronized void           removeElementAt(int location)
synchronized boolean        retainAll(Collection<?> collection)
synchronized E              set(int location, E object)
synchronized void           setElementAt(E object, int location)
synchronized void           setSize(int length)
synchronized int            size()
synchronized List<E>        subList(int start, int end)
synchronized <T> T[]        toArray(T[] contents)
synchronized Object[]       toArray()
synchronized String         toString()
synchronized void           trimToSize()

参考博文:
1.Java 集合系列06之 Vector详细介绍(源码解析)和使用示例

猜你喜欢

转载自blog.csdn.net/qq_38425803/article/details/107152376