【Java1.7.5集合源码剖析】Vector源码剖析

Vector简介

    Vector也是基于数组实现的,是一个动态数组,其容量能自动增长。

    Vector是JDK1.0引入了,它的很多实现方法都加入了同步语句,因此是线程安全的(其实也只是相对安全,有些时候还是要加入同步语句来保证线程的安全),可以用于多线程环境。

    Vector继承Serializable接口,因此它支持序列化,实现了Cloneable接口,能被克隆,实现了RandomAccess接口,支持快速随机访问,Clone: 
简单的说就是clone一个对象实例。使得clone出来的copy和原有的对象一模一样 

Vector特点: 
1.内部通过数组实现 
2.通过synchronized同步方法,线程安全,适合多线程 
3.由于线程安全,效率不高 
4.默认存放10个元素 
5.需要增加容量时候,默认新增加容量是元素Vector的大小 

6.支持为NULL

7.效率低,不推荐用 

public class Vector
   
   
    
    
    extends AbstractList
    
    
     
     
    implements List
     
     
      
      , RandomAccess, Cloneable, java.io.Serializable
{
    //内部通过Object数组存放元素
    protected Object[] elementData;

    //当前元素id
    protected int elementCount;

    //每次可增加容量大小
    protected int capacityIncrement;

    //序列号
    private static final long serialVersionUID = -2767605614048989439L;

    /**
     * 构造器 
     * @param initialCapacity    默认数组大小 
     * @param capacityIncrement   可增加容量大小
     */
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        //下标不合法抛异常
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        // 新建一个数组,数组容量是initialCapacity  
        this.elementData = new Object[initialCapacity];
        // 设置容量增长系数  
        this.capacityIncrement = capacityIncrement;
    }

    // 指定Vector容量大小的构造函数   
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    //Vector构造函数。默认容量是10。
    public Vector() {
        this(10);
    }

    //指定集合的Vector构造函数。 
    public Vector(Collection
      
       c) {
    	 // 获取“集合(c)”的数组,并将其赋值给elementData    
        elementData = c.toArray();
        // 设置数组长度    
        elementCount = elementData.length;
        
        if (elementData.getClass() != Object[].class)
        	//拷贝一个数组赋值
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }
     //下面方法都加了synchronized用来保证线程安全
    
    // 将数组Vector的全部元素都拷贝到数组anArray中   
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

    //修剪elementData,保证其内部的元素都是有效元素 
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {  
        	//elementCount 记录实际元素个数
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    //增加容量
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    //根据Vector长度和判断是否需要增加容量
    private void ensureCapacityHelper(int minCapacity) {
        if (minCapacity - elementData.length > 0)
        	// 当Vector的容量不足以容纳当前的全部元素,增加容量大小。 
            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
            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) 
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    //可以看出:当不指定扩充容量的最小值时候,每次新增加的容量大小等于原始Vector的大小
    //设置大小,根据程序,使得newSize以后的元素清楚,只保留newsize个元素。当不足newsize个元素的时候,需要进行扩充
    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;
    }
    
    /**
     * 注意两个的区别: 
     * 容量可能比较大,个数指的是具体元素的个数 
     * 容量只能够存放元素个数的最大值
     */ 

    //获取当前Vector的容量
    public synchronized int capacity() {
        return elementData.length;
    }

    //获取当前Vector元素的个数
    public synchronized int size() {
        return elementCount;
    }

    //判断是否为空
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

    //获取一个Enumeration类型的组件,可以顺序的访问Vector元素,这个和迭代器很类似
    public Enumeration
      
      
       
        elements() {
        return new Enumeration
       
       
         () { 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"); } }; } //判断是否包含元素 o public boolean contains(Object o) { return indexOf(o, 0) >= 0; } //返回元素 o 第一次出现的下标 public int indexOf(Object o) { return indexOf(o, 0); } //从index开始,查找元素o出现的下标 当不出现的时候返回-1 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); } //截止到index,返回元素o 最后一次出现的下标 不出现,返回-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; } //返回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位置元素 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) { // elementData数组,从index+1开始复制j个元素,到该数组的index开始位置 System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; // 元素个数-1 elementData[elementCount] = null; // 空,有利于垃圾回收 } //index位置插入元素 o 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++; // 元素个数 + 1 } //尾部插入元素 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; } //删除所有元素 public synchronized void removeAllElements() { modCount++; // Let gc do its work for (int i = 0; i < elementCount; i++) elementData[i] = null; //循环设置为null elementCount = 0; //清空元素数量为0 } // clone一个Vector public synchronized Object clone() { try { @SuppressWarnings("unchecked") Vector 
        
          v = (Vector 
         
           ) super.clone(); v.elementData = Arrays.copyOf(elementData, elementCount); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { throw new InternalError(); } } //Vector元素复制到数组 public synchronized Object[] toArray() { return Arrays.copyOf(elementData, elementCount); } //Vector中元素复制到指定数组 @SuppressWarnings("unchecked") public synchronized 
          
            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位置元素 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 boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); //调整大小 elementData[elementCount++] = e;//赋值 return true; } //删除元素 public boolean remove(Object o) { return removeElement(o); } //index位置插入元素 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(); } //Vector内是否包含集合c的元素 public synchronized boolean containsAll(Collection 
            c) { return super.containsAll(c); } //集合c中元素添加到Vector中 public synchronized boolean addAll(Collection 
            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; } //Vector集合 与集合c的差集 public synchronized boolean removeAll(Collection 
            c) { return super.removeAll(c); } //交集 public synchronized boolean retainAll(Collection 
            c) { return super.retainAll(c); } //index位置插入集合c的元素 public synchronized boolean addAll(int index, Collection 
            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; } //重写equals方法 public synchronized boolean equals(Object o) { return super.equals(o); } //hashcode方法 public synchronized int hashCode() { return super.hashCode(); } //转化为字符串 public synchronized String toString() { return super.toString(); } //返回区间内的元素,并保存在List中 public synchronized List 
           
             subList(int fromIndex, int toIndex) { return Collections.synchronizedList(super.subList(fromIndex, toIndex), this); } //删除区间内的元素 protected synchronized void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = elementCount - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, 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(); } //获取从index开始的迭代器 public synchronized ListIterator 
            
              listIterator(int index) { if (index < 0 || index > elementCount) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } //获取所有元素的迭代器 public synchronized ListIterator 
             
               listIterator() { return new ListItr(0); } //获取所有元素的迭代器 public synchronized Iterator 
              
                iterator() { return new Itr(); } //ListItr迭代器与Itr迭代器区别 //ListItr继承Itr,并增加了前驱遍历的方法,也可以添加元素 //Itr只能向后遍历 //Itr private class Itr implements Iterator 
               
                 { 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(); } } //ListItr final class ListItr extends Itr implements ListIterator 
                
                  { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public E 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 e) { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.set(lastRet, e); } } public void add(E e) { int i = cursor; synchronized (Vector.this) { checkForComodification(); Vector.this.add(i, e); expectedModCount = modCount; } cursor = i + 1; lastRet = -1; } } } 
                 
                
               
              
             
            
           
          
         
       
      
      
     
     
    
    
   
   



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值