5-2、java.util.Vector

5-2、java.util.Vector


package java.util;
public class Vector<Eextends AbstractList<E>
        implements List<E>RandomAccessCloneablejava.io.Serializable
{
    protected Object[] elementData;
    protected int elementCount;
    protected int capacityIncrement;
    private static final long serialVersionUID = -2767605614048989439L;
    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(initialCapacity0);}
    public Vector() {this(10);}
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount elementData.length;
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementDataelementCountObject[].class);
    }
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData0anArray0elementCount);
    }
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementDataelementCount);
        }
    }
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }
    private void ensureCapacityHelper(int minCapacity) {
        if (minCapacity - elementData.length 0)
            grow(minCapacity);
    }
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE 8;

    private void grow(int minCapacity) {
        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(elementDatanewCapacity);
    }
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0)
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE MAX_ARRAY_SIZE;
    }
    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;}
    public Enumeration<Eelements() {
        return new Enumeration<E>() {
            int count 0;
            public boolean hasMoreElements() {
                return count elementCount;
            }
            public nextElement() {
                synchronized (Vector.this) {
                    if (count elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }
    public boolean contains(Object o) {return indexOf(o0) >= 0;}
    public int indexOf(Object o) {return indexOf(o0);}
    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(oelementCount-1);}
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "elementCount);
        if (o == null) {
            for (int i = indexi >= 0i--)
                if (elementData[i]==null)
                    return i;
       else {
            for (int i = indexi >= 0i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    public synchronized elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " elementCount);
        }
        return elementData(index);
    }
    public synchronized firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }
    public synchronized lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount 1);
    }
    public synchronized void setElementAt(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(elementDataindex + 1elementDataindexj);
        }
        elementCount--;
        elementData[elementCount] = null; /* to let gc do its work */
    }
    public synchronized void insertElementAt(obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                    + " > " elementCount);
        }
        ensureCapacityHelper(elementCount 1);
        System.arraycopy(elementDataindexelementDataindex + 1elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }
    public synchronized void addElement(obj) {
        modCount++;
        ensureCapacityHelper(elementCount 1);
        elementData[elementCount++] = obj;
    }
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }
    public synchronized void removeAllElements() {
        modCount++;
        for (int i = 0i < elementCounti++)
            elementData[i] = null;
        elementCount 0;
    }
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementDataelementCount);
            v.modCount 0;
            return v;
       catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }
    public synchronized Object[] toArray() {return Arrays.copyOf(elementDataelementCount);}
    @SuppressWarnings("unchecked")
    public synchronized <TT[] toArray(T[] a) {
        if (a.length elementCount)
            return (T[]) Arrays.copyOf(elementDataelementCounta.getClass());
        System.arraycopy(elementData0a0elementCount);
        if (a.length elementCount)
            a[elementCount] = null;
        return a;
    }
    @SuppressWarnings("unchecked")
    elementData(int index) {
        return (EelementData[index];
    }
    public synchronized get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        return elementData(index);
    }
    public synchronized set(int indexelement) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
    public synchronized boolean add(e) {
        modCount++;
        ensureCapacityHelper(elementCount 1);
        elementData[elementCount++] = e;
        return true;
    }
    public boolean remove(Object o) {return removeElement(o);}
    public void add(int indexelement) {insertElementAt(elementindex);}
    public synchronized remove(int index) {
        modCount++;
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        oldValue = elementData(index);
        int numMoved = elementCount - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementDataindex+1elementDataindexnumMoved);
        elementData[--elementCount] = null;
        return oldValue;
    }
    public void clear() {removeAllElements();}
    public synchronized boolean containsAll(Collection<?> c) {return super.containsAll(c);}
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);
        System.arraycopy(a0elementDataelementCountnumNew);
        elementCount += numNew;
        return numNew != 0;
    }
    public synchronized boolean removeAll(Collection<?> c) {return super.removeAll(c);}
    public synchronized boolean retainAll(Collection<?> c) {return super.retainAll(c);}
    public synchronized boolean addAll(int indexCollection<? extends E> c) {
        modCount++;
        if (index < || 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(elementDataindexelementDataindex + numNew,
                    numMoved);
        System.arraycopy(a0elementDataindexnumNew);
        elementCount += numNew;
        return numNew != 0;
    }
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }
    public synchronized int hashCode() {
        return super.hashCode();
    }
    public synchronized String toString() {
        return super.toString();
    }

    public synchronized List<EsubList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndextoIndex), this);
    }
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = elementCount - toIndex;
        System.arraycopy(elementDatatoIndexelementDatafromIndex,
                numMoved);
        int newElementCount = elementCount - (toIndex-fromIndex);
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }
    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();
    }
    public synchronized ListIterator<ElistIterator(int index) {
        if (index < || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }
    public synchronized ListIterator<ElistIterator() {
        return new ListItr(0);
    }
    public synchronized Iterator<Eiterator() {
        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() {
            return cursor != elementCount;
        }
        public 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();
        }
    }
    final class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }
        public boolean hasPrevious() {
            return cursor != 0;
        }
        public int nextIndex() {
            return cursor;
        }
        public int previousIndex() {
            return cursor 1;
        }
        public previous() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor 1;
                if (i < 0)
                    throw new NoSuchElementException();
                cursor = i;
                return elementData(lastRet = i);
            }
        }
        public void set(e) {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.set(lastRete);
            }
        }
        public void add(e) {
            int i = cursor;
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.add(ie);
                expectedModCount modCount;
            }
            cursor = i + 1;
            lastRet = -1;
        }
    }
}

//说明:
Vector 类可以实现可增长的对象数组。
与数组一样,它包含可以使用整数索引进行访问的组件。
但是,Vector 的大小可以根据需要增大或缩小,以适应创建 Vector 后进行添加或移除项的操作。
每个向量会试图通过维护 capacity 和 capacityIncrement 来优化存储管理。
capacity 始终至少应与向量的大小相等;这个值通常比后者大些,因为随着将组件添加到向量中,其存储将按 capacityIncrement 的大小增加存储块。
应用程序可以在插入大量组件前增加向量的容量;这样就减少了增加的重分配的量。
由 Vector 的 iterator 和 listIterator 方法所返回的迭代器是快速失败的:
如果在迭代器创建后的任意时间从结构上修改了向量(通过迭代器自身的 remove 或 add 方法之外的任何其他方式),则迭代器将抛出 ConcurrentModificationException。
因此,面对并发的修改,迭代器很快就完全失败,而不是冒着在将来不确定的时间任意发生不确定行为的风险。
Vector 的 elements 方法返回的 Enumeration 不是 快速失败的。
注意,迭代器的快速失败行为不能得到保证,一般来说,存在不同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。
因此,编写依赖于此异常的程序的方式是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测 bug。
与新 collection 实现不同,Vector 是同步的

Vector() :构造一个空向量,使其内部数据数组的大小为 10,其标准容量增量为零。
Vector(Collection<? extends E> c)
  构造一个包含指定 collection 中的元素的向量,这些元素按其 collection 的迭代器返回元素的顺序排列。
Vector(int initialCapacity): 使用指定的初始容量和等于零的容量增量构造一个空向量。
Vector(int initialCapacity, int capacityIncrement): 使用指定的初始容量和容量增量构造一个空的向量。
protected intcapacityIncrement : 向量的大小大于其容量时,容量自动增加的量。
protected int elementCount: Vector 对象中的有效组件数。
protected Object[] elementData:存储向量组件的数组缓冲区。

//如下代码:使用同步
public synchronized List<E> subList(int fromIndex, int toIndex) {
  return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值