Vector源码阅读

Stack的父类Vector源码阅读

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

首先看这个Vector类继承了RandomAccess;所以是支持快速随机访问的
其次是继承了Cloneable所以是可克隆的;
又是继承了Java.io.Serializable 所以是可以进行序列化 反序列化的;
由于这个类也属于Collection 则可以用for-each进行遍历;

Vector类的成员变量
    //这里用一个数组来存储Vector容器的元素,这个数组的大小一定要比能够存储的元素的数量要大,
    //当然这个数组的大小有可能有部分空间是空的,用null来表示;
    protected Object[] elementData;
    //实际这个对象所存储的元素的个数;
    //elementData[elementCount-1]是实际有的元素;
    protected int elementCount;
    
    protected int capacityIncrement;
    //自定义了 serialVersionUID 保证序列化版本的一致性
    private static final long serialVersionUID = -2767605614048989439L;
Vector类的构造函数
//@param initialCapacity(不小于0) 初始化的容器大小
//@param 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;
    }

//@param initialCapacity 初始化容器大小
//会构造一个初始化容量为指定参数大小,扩容因子为0的Vector类
 public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

//默认的无参构造函数,会构造一个初始容器大小为10,扩容因子为0的Vector对象
 public Vector() {
        this(10);
    }  
  
 //@param  @NotNull Collection c 指定一个Collection类型的集合来创建Vector
 // 把一个Collection类型的集合转化为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类的扩容方法

所以每个Vector的对象进行扩容时,都是线程安全的,
既多个线程同时对一个Vector对象进行扩容时会造成堵塞;

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 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
   
    //Vector类的扩容操作
    //如果扩容因子大于0则每次扩容增加扩容因子的大小
    //不然则在原有大小的基础上增加一倍
    //如果以上扩容后比想扩容的大小小,则扩容至想要的大小
    //不能超过Integer.MAX_VALUE
    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);
    }

    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 一个Object类型的数组对象
//把Vector对象中的元素复制到指定参数的数组对象中去
public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }
    
    
//这个方法是把原本多出来空间的Vector容器对象的多处来的空间减少成刚好装满的状态 
public synchronized void trimToSize() {
        modCount++;//这里主要是为了在遍历的时候避免并发错误
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }
//公共的方法  modCount++;   
//如果指定的大小大于当前的元素的个素,将容器的容量改变成指定大小
//如果指定的大小不大于当前元素的个数,把指定参数大小以外的元素都设置为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;
    }
    
//返回集合的实际的元素的个数 
public synchronized int size() {
        return elementCount;
    }
//是否不包含元素    
public synchronized boolean isEmpty() {
        return elementCount == 0;
    }
//调用此方法可以获取一个枚举对象类
//可以通过此方法进行遍历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 boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

Vector类的增删改查
由于查找不会影响到modCount先来看查找元素的代码
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

   
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    
    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 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 firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

   
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

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

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

        return elementData(index);
    }

    

这里的查找跟ArrayList是类似的,查找速度比较快,空间复杂度在O(n),一个循环就能找到
区别是所有方法都加了synchronized 此外多了一个从某个索引开始找某个元素是否存在;

Vector删除修改增加元素的方法

删除某个索引的元素 删除某个元素 删除所有元素(设置所有元素为null为了垃圾回收)
将某个索引上的元素进行修改(唯一没有modCount++的方法)
增加元素 在某个索引后增加元素(有可能会进行扩容)

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

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
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++;
    }

    
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
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;
    }

     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 removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }
    
     public void clear() {
        removeAllElements();
    }


    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();
    }
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }
    //这个方法是调用了了父抽象类AbstractCollection的removeAll方法
     //把Vector对象中包含集合c的元素给去除掉
     //注意在遍历时调用的是Vector对象的迭代器进行遍历;
     //保留的元素是集合c中不存在的	;
        public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

    //这个方法是调用了父抽象类AbstractCollection的retainAll方法
    //将参数c集合中不包含的元素去除,只保留原本Vector对象中c集合中也有的元素;
    //注意在遍历时调用的是Vector对象的迭代器进行遍历;
    //遍历过程中如果c集合中不包含此元素就去除;留下c集合中包含的元素 并返回一个布尔值;
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }
    //这是AbstractCollection中的retainAll方法;
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            if (!c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }
    //这个方法是调用了父抽象类AbstractCollection的containsAll方法
    //用来判断是否包含集合c的所有元素
    //底层也是用了迭代器;
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }
    //这个方法是protected(子类或者同一个包可调用) 并且是同步的方法
    //删除从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;
    }

这里增删改的核心思想其实都是类似的,种类也比较多
增加
可以在指定的索引增加元素,甚至增加集合;
注意的是每次增加都会有一个确保容量的操作,可能会发生扩容;
在中间进行插入会造成数组复制的这么一个情况;
如果是插入集合,会调用.toArray();方法转换为数组
删除
删除的时候设计到一个将元素删除,设置为null,让JVM进行垃圾回收
如果是在中间索引会涉及数组的一个复制
修改
修改比较简单,只是的把数组对应索引上的元素给更新

以上有几个方法可以注意:
public synchronized boolean retainAll(Collection<?> c),只保留集合c中有的元素
public synchronized boolean containsAll(Collection<?>c),判断是否包含c集合中的所有元素
public sunchronized boolean removeAll(Collection<?>c),把集合c中包含的元素都移除掉
这三个方法都是利用了迭代器进行操作~
另外有一个protected的方法
protected synchronized void removeRange(int fromIndex, int toIndex)
这个方法在直接构造Vector对象时是不能被使用的,
可以自己实现一个List的时候继承使用 ,
实际上这里是用到了subList来实现
ArrayList ints = new ArrayList(Arrays.asList(0, 1, 2,
3, 4, 5, 6));
ints.subList(2, 4).clear();
SubList的clear()方法就是调用了这个removeRange方法将所有元素移除;

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

   
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    
    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;
    }
   @Override
    public synchronized void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int elementCount = this.elementCount;
        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final int size = elementCount;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            elementCount = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = elementCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, elementCount, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
/**
     * Loads a {@code Vector} instance from a stream
     * (that is, deserializes it).
     * This method performs checks to ensure the consistency
     * of the fields.
     *
     * @param in the stream
     * @throws java.io.IOException if an I/O error occurs
     * @throws ClassNotFoundException if the stream contains data
     *         of a non-existing class
     */
    private void readObject(ObjectInputStream in)
            throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField gfields = in.readFields();
        int count = gfields.get("elementCount", 0);
        Object[] data = (Object[])gfields.get("elementData", null);
        if (count < 0 || data == null || count > data.length) {
            throw new StreamCorruptedException("Inconsistent vector internals");
        }
        elementCount = count;
        elementData = data.clone();
    }

    /**
     * Save the state of the {@code Vector} instance to a stream (that
     * is, serialize it).
     * This method performs synchronization to ensure the consistency
     * of the serialized data.
     */
    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();
    }

还有SubList
private class Itr implements Iterator
final class ListItr extends Itr implements ListIterator
分裂迭代为了并行遍历

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值