Vector源码学习

 

安全的可增长数组结构


实现:
1. 内部采用数组的方式。
  1.1 添加元素,会每次校验容量是否满足, 扩容规则有两种,1.增加扩容补偿的长度,2.按照现有数组长度翻一倍。容量上限是Integer.MAX_VALUE。 copy使用Arrays.copy的api
  1.2 删除元素
    1.2.1 通过对象删除。遍历数组,删除第一个匹配的对象
    1.2.3 通过下标删除。判断下标是否越界。
      使用 System.arraycopy进行copy, 并将元素的最后一位设置为null.供gc回收
2. 内部是同步[modCount]
  2.1 ArrayList数据结构变化的时候,都会将modCount++。
  2.2 采用Iterator遍历的元素, next()会去检查集合是否被修改[checkForComodification],如果集合变更会抛出异常
  类似于数据库层面的 乐观锁 机制。 可以通过 Iterator的api去删除元素
3. 数组结构,内部存储数据是有序的,并且数据可以为null,支持添加重复数据
4. 线程安全的, 关于数组的增删方法都采用了synchronized标注。

 

源码学习

// 自动增长的对象数组
public class Vector<E> {

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    // 元素数组
    protected Object[] elementData;
    
    // 元素长度
    protected int elementCount;
    
    // 扩容步长[增长容量]
    protected int capacityIncrement;
    
    // 集合变更次数
    private int modCount = 0;
    
    
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);     // 10个长度,步长为0 
    }
    
    public Vector() {
        this(10);  // 默认10个长度
    }
    
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)      // 初始化容量 小于0  抛异常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];   // 创建指定长度数组
        this.capacityIncrement = capacityIncrement;   // 增长容量大小
    }
    
    // 添加元素
    public synchronized boolean add(E element) {

        modCount++;
        ensureCapacityHelper(elementCount + 1);  // 校验当前容器容量是否满足
        elementData[elementCount++] = element;
        return true;
    }
    
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }
    
    private void ensureCapacityHelper(int minCapacity) {
        if (minCapacity - elementData.length > 0)   // 当前下标  > 数组长度
            grow(minCapacity);
    }

   // 扩容方法
private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); // 如果步长大于0, 每次扩容步长大小,否则按数组的长度翻一倍 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; } public boolean remove(Object o) { return removeElement(o); } 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 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; } private synchronized boolean removeElement(Object obj) { if (obj == null) { for (int index = 0; index < elementCount; index++) if (elementData[index] == null) { // 删除 null fastRemove(index); return true; } } else { for (int index = 0; index < elementCount; index++) if (obj.equals(elementData[index])) { // eqals比较 fastRemove(index); return true; } } return false; } 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 */ } private void fastRemove(int index) { modCount++; int numMoved = elementCount - index - 1; // 当前size - index - 1 数组从0开始 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); // system arraycopy elementData[--elementCount] = null; // clear to let GC do its work gc回收 数组最后一个元素设置为null } public synchronized Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { // Racy but within spec, since modifications are checked // within or after synchronization in next/previous return cursor != elementCount; } public E next() { synchronized (Vector.this) { checkForComodification(); int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); cursor = i + 1; return elementData(lastRet = i); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.remove(lastRet); expectedModCount = modCount; } cursor = lastRet; lastRet = -1; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return elementData(index); } @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } public int size() { return elementCount; } }

 

posted on 2018-11-29 14:39  Luis、Yang、  阅读(104)  评论(0编辑  收藏  举报

导航