Vector源码

Vector与ArrayList类似,都是使用动态数组实现
Vector是线程安全的
 
重要说明:
1、实现AbstractList,即List的抽象类
2、使用数组存储数据
3、默认初始化大小为10
4、Vector中有capacityIncrement属性:
capacityIncrement>0,newCapacity=原有容量+capacityIncrement
capacityIncrement=0,newCapacity=2 * capacityIncrement
5、对于数组的都修改都增加synchronize同步关键字
 
代码翻译:
public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

    实际用于存储Vector数据的数组
    protected Object[] elementData;

    Vector大小
    protected int elementCount;

     当Vector的size大于容量时,Vector容量自动增加capacityIncrement
     如果容量增加量小于等于0,则Vector容量变为2倍
    protected int capacityIncrement;

    定义初始容量和增加量
    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);
    }

    默认10容量大小
    public Vector() {
        this(10);
    }

    将集合c转为数组
    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);
    }
    将数组对象拷贝到elementData中
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

    根据elementCount整理elementData数组大小
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    如果最小容量>0,则扩容
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

     如果最小容量-当前容量>0,则扩容
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    Vector最大数量
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
    //根据minCapacity扩展数组容量,
    //先获得当前数组容量oldCapacity,
    //如果capacityIncrement > 0则newCapacity大小=(oldCapacity+capacityIncrement),否则newCapacity大小=(oldCapacity+oldCapacity)
    //如果newCapacity-minCapacity<0,则设置elementData为minCapacity大小
    //如果newCapacity-数组允许的最大值>0,则调用hugeCapacity方法进行扩容
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        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);
    }


    //如果最新容量小于0,报错内存溢出
    //否则设置最小容量>MAX_ARRAY_SIZE,则数组大小设置为Integer最大值,否则设置为(Integer最大值-8)
    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大小,如果newSize大于原有数组大小,则进行扩容,
    如果newSize小于等于elementCount,则把elementCount-newSize剩余的索引设置为null
    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 int capacity() {
        return elementData.length;
    }

    同步返回vector容量
    public synchronized int size() {
        return elementCount;
    }

    判断vector容量是否为0
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }
    
    数组中是否包含o对象
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    返回o对象所在的索引
    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;
    }

    同步的返回o对象最后出现的索引
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    同步的返回o对象从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;
    }

    同步返回index索引的数据
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

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

    在index索引的值设置为obj
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        elementData[index] = obj;
    }

    删除index索引的值,通过拷贝的方式
    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 */
    }
    
    在index索引位置插入obj对象,通过拷贝的方式
    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++;
    }

    在数组最后添加obj对象,判断是否需要进行扩容
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    删除是数组中第一个等于obj的值的数据
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    把数组所有值设置为null,容量设置为0
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    克隆方法,元素本身不会被复制,只拷贝了指针,克隆后的数组与原有数组相同
    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);
    }

    返回数组
    @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;
    }

    返回index索引的值
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    返回index索引的值
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    把index索引的值设置为element
    public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    在数组最后增加e对象
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

    删除o对象
    public boolean remove(Object o) {
        return removeElement(o);
    }

    在index索引插入element对象
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    通过拷贝的方式删除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;
    }

    清空数组
    public void clear() {
        removeAllElements();
    }

    // Bulk Operations

    调用ArrayList中的包含方法
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    把集合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;
    }

    调用ArrayList中的删除方法:根据集合批量删除数据
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    调动ArrayList中的方法:根据集合批量保留数组中的数据:数组中在c集合中存在的对象
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    在指定索引添加集合c
    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;
    }
}
 
收藏文章数量从多到少与“把书读薄”是一个道理
原文地址:https://www.cnblogs.com/use-D/p/9589322.html