Java基础学习之java.util包(三):Vector类

 Vector 类

// 存放Vector中数据的数组
protected Object[] elementData;

// 实际数组大小(数组已使用的大小)
protected int elementCount;

//扩容量
protected int capacityIncrement;

四种构造方法:
/*initialcapacity capacityIncrement 扩容量,capacityIncrement为0时,则每次扩充一倍*/ //初始设定容量、扩容量值 public vector(int initialcapacity,int capacityIncrement) //初始设定容量值 扩容默认0每次扩充一倍 public vector(int initialcapacity) //初始默认容量10 扩容默认0每次扩充一倍 public vector() //传入集合参数 获取Collection<? extends E> c的数组,并将其赋值给Vector数组elementData public Vector(Collection<? extends E> c)

 

 源码解析:

//将数组elementData 的全部元素都拷贝到数组 anArray中  
public synchronized void copyInto(Object[] anArray) 
{        
    //通过System.arraycopy 完成复制
    System.arraycopy(elementData, 0, anArray, 0, elementCount);
}

/*修改该向量的容量成为向量的当前大小(将当前容量值设为 =实际元素个数)
 方法说明:Vector默认扩容是当前容量大小的2倍,
  扩容后的容量如果不需要这么多(当前数组实际大小elementCount < 扩容后容量 ),
  通过调用当前方法修改容量为实际元素数量大小。
 作用:释放掉未使用的容量 重置elementData 数组元素
*/
public synchronized void trimToSize() 
{
  // modCount++ 统计Vector的修改次数
   modCount++;
   int oldCapacity = elementData.length;
  //当前数组实际大小elementCount < 扩容后容量 elementData.length
   if (elementCount < oldCapacity) {
  // 通过elementCount设置elementData数组大小 重置elementData数组元素(Arrays.copyOf 复制新的数组)
    elementData = Arrays.copyOf(elementData, elementCount);
   }
}

/*minCapacity 设置扩容量
 当要扩容时,会调用此方法,保证当前容量能存放得下所需要存放的元素数量。
*/
public synchronized void ensureCapacity(int minCapacity) 
{
 //大于0继续
  if (minCapacity > 0) {
  // modCount++ 统计Vector的修改次数
    modCount++;
  //调用ensureCapacityHelper 传入minCapacity
    ensureCapacityHelper(minCapacity);
  }
}

/*
如果容量不够,会调用grow()方法进行扩容
*/
 private void ensureCapacityHelper(int minCapacity) 
{
  // 当前容量(minCapacity )比数组的长度(elementData.length)小 调用grow 扩容
  if (minCapacity - elementData.length > 0)
    grow(minCapacity);
 }

//MAX_ARRAY_SIZE 底层数组最大元素
 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

 private void grow(int minCapacity) 
{
  //获取到elementData[]数组的长度 原始容量
  int oldCapacity = elementData.length;
  //如果设置capacityIncrement扩容量,新的容量=原始容量+扩容量(newCapacity = oldCapacity + capacityIncrement)
  //如果没设置,新的容量=原始容量的2倍(newCapacity = oldCapacity+oldCapacity)
  int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
  //新的容量 < 元素数量 设置新的容量=元素数量
  if (newCapacity - minCapacity < 0)
    newCapacity = minCapacity;
  //新的容量 > 最大容量 调用hugeCapacity()重新分配容量
  if (newCapacity - MAX_ARRAY_SIZE > 0)
    newCapacity = hugeCapacity(minCapacity);
  //把elementData中的元素都拷贝到一个新的容量为newCapacity的数组中去,然后再赋值给elementData,完成扩容
  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;
}

/*
  修改容量,当newSize比数组的长度要大时,将其复制到新的内存区域,如果要小的话,则从newSize位置到数组的最后一个位置的所有元素置为空
*/
 public synchronized void setSize(int newSize) 
{

     // modCount++ 统计Vector的修改次数
        modCount++;
     //newSize比数组的长度大 做扩容相关操作
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else {
       //newSize比数组的长度小, 数组newSize到elementData[elementCount]之间的数据置为null
            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;
}

/*
判断Vector是否为空  
*/
 public synchronized boolean isEmpty() 
{
 //判空,如果数量为0,即为empty
  return elementCount == 0;
}

/*
返回一个Enumeration对象的序列。Enumeration只有两个方法,hasMoreElements()和nextElement(),它只能从首个元素遍历到最后一个元素,并不能根据位置拿到具体的元素。
*/
public Enumeration<E> elements() 
{
        return new Enumeration<E>() {//匿名内部类
            int count = 0;//初始值0
       //重写hasMoreElements();count < elementCount,还有下一个元素存在 
       //当前方法判断 是否还有下一个元素存在
            public boolean hasMoreElements() {
                return count < elementCount;
            }
       //同上 count < elementCount,返回下一个元素否则抛出异常
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
  }

/*
 判断Vector中是否包含对象(o)
  从index位置开始向后查找元素(o)
*/
public boolean contains(Object o) 
{
 //是否包含对象o。调用indexOf判断是否存在
  return indexOf(o, 0) >= 0;
}
 //indexOf()方法==>判断o是否存在
 public int indexOf(Object o) 
{
        return indexOf(o, 0);
}
// 判断o是否为空,如果为空,则遍历是否存在值为空的元素;不为空,判断是否存在和o相等的元素。
//从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 {
        //从index位置开始向后查找元素(o)
            for (int i = index ; i < elementCount ; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
  }
/*
   判断Vector中是否包含对象(o)
   从elementCount-1位置开始向前查找元素(o)
*/
public synchronized int lastIndexOf(Object o) 
{
        return lastIndexOf(o, elementCount-1);
}
//从后向前若找到,则返回元素的索引值;否则,返回-1 
public synchronized int lastIndexOf(Object o, int index) 
{
    //判断index > elementCount抛出异常
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
     // 判断o是否为空,如果为空,则遍历是否存在值为空的元素;
        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
       //不为空,判断是否存在和o相等的元素
            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);
    }

/*
  获取第一个元素
  根据index下标获取元素,下标为0
*/
    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

/*
  最后第一个元素
  根据index下标获取元素,下标为elementCount - 1
*/
    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;
    }
/*
  移除指定位置元素  
*/
 public synchronized void removeElementAt(int index) {
    // modCount++ 统计Vector的修改次数
        modCount++;
     //数组越界 超出数组实际大小
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +elementCount);
        }
     ////数组越界 数组下标从0开始
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
     // j 需要移动的个数
        int j = elementCount - index - 1;
        if (j > 0) {
       //把elementData 的元素从index+1开始的j个元素往前移 
       //通过System.arraycopy复制元素 完成元素移动
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }

     //更新数组实际大小
        elementCount--;
     //把数组最后一个元素赋值为null 最后由gc垃圾回收机制处理
        elementData[elementCount] = null; /* to let gc do its work */
    }
/*
  对指定位置添加新的元素
*/
public synchronized void insertElementAt(E obj, int index) 
{
    // modCount++ 统计Vector的修改次数
        modCount++;
     //数组越界 超出数组实际大小
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index+ " > " + elementCount);
        }
     //扩容操作 数组实际容量+1
        ensureCapacityHelper(elementCount + 1);
        //把elementData 的元素从index开始的(elementCount - index)个元素往后移
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
     //index 位置插入新的元素
        elementData[index] = obj;
     //更新数组实际大小
        elementCount++;
    }

 /*
  新增数组元素
*/
 public synchronized void addElement(E obj) {
    // modCount++ 统计Vector的修改次数
        modCount++;
     //扩容操作 数组实际容量+1
        ensureCapacityHelper(elementCount + 1);
     //新增元素放入新的位置 (elementCount++ 为扩容后数组元素最后一位下标,也是新扩容的位置)
        elementData[elementCount++] = obj;
    }

/*
  移除obj元素 ,返回boolean类型
*/
 public synchronized boolean removeElement(Object obj) {
     // modCount++ 统计Vector的修改次数
        modCount++;
     //indexOf() 方法获取obj元素下表,存在返回元素下标,不存在返回-1
        int i = indexOf(obj);
        if (i >= 0) {
       //存在移除指定位置元素
            removeElementAt(i);
            return true;
        }
        return false;
    }
/*
  移除所有元素
*/
  public synchronized void removeAllElements() {
     //modCount++ 统计Vector的修改次数
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;// 等待GC 
        elementCount = 0;
    }

/*
  克隆方法 复制一个新的Vector 并返回
*/
 public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
       //super.clone是克隆当前对象生成一个新的副本,调用父类方法实现浅克隆
            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();
        }
    }

/*
  返回Object数组
*/
  public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }
/*
  返回指定类型数组
*/
  public synchronized <T> T[] toArray(T[] a) {
     //a数组长度 < 实际数组长度; Arrays.copyOf 复制一个新的数组 类型为a数组类型
        if (a.length < elementCount)
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
     //数组a的大小 >=实际数组长度(elementData); 把elementData[] 元素 复制到a[]
        System.arraycopy(elementData, 0, a, 0, elementCount);
        if (a.length > elementCount)
     a[elementCount] = null;
        return a;
    }

  //获取elementData[index] 元素 返回一个Element元素
   E elementData(int index) {
        return (E) elementData[index];
    }

 //根据下标获取Element元素
  public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
   }

  //根据下标重置index位置元素,并返回index位置的原始值
  public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
     //保存原始值
        E oldValue = elementData(index);
    //设置elementData[]数组index位置的值为element
        elementData[index] = element;
     //返回原始值
        return oldValue;
    }
/*
  将“元素e”添加到Vector最后。 
*/
public synchronized boolean add(E e) 
{
    //modCount++ 统计Vector的修改次数
        modCount++;
     //扩容+1
        ensureCapacityHelper(elementCount + 1);
     //新扩容的位置为e元素
        elementData[elementCount++] = e; 
        return true;
  }
  
 //移除o元素
  public boolean remove(Object o) {
      //调用removeElement()移除元素
        return removeElement(o);
    }
  
 //添加元素
 public void add(int index, E element) {
     //调用insertElementAt()添加新元素
        insertElementAt(element, index);
    }

//删除index下标元素 返回原始值
 public synchronized E remove(int index) {
  //modCount++ 统计Vector的修改次数
        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;
    }
/*
  清空Vector
*/
 public void clear() 
{
     //调用removeAllElements()清除 数组元素
        removeAllElements();
}

//判断Vector中是否包含Collection<?> c
public synchronized boolean containsAll(Collection<?> c) 
{
     //返回Vector是否包含集合c 
        return super.containsAll(c);
 }

/*
  添加一个集合到当前数组
*/
public synchronized boolean addAll(Collection<? extends E> c) {
    //modCount++ 统计Vector的修改次数
        modCount++;
     //c集合转换成数组
        Object[] a = c.toArray();
     //集合数组长度 扩容使用
        int numNew = a.length;
     //扩容
        ensureCapacityHelper(elementCount + numNew);
     //通过System.arraycopy 完成数据添加 把a[]从0开始复制 elementData[]从elementCount开始 复制数量numNew
        System.arraycopy(a, 0, elementData, elementCount, numNew);
     //修改实际数组大小
        elementCount += numNew;
        return numNew != 0;
 }

//删除集合c的全部元素
public synchronized boolean removeAll(Collection<?> c) 
{
    return super.removeAll(c);
}
 // 删除“非集合c中的元素”
 public synchronized boolean retainAll(Collection<?> c) {
  return super.retainAll(c);
}

// 从index位置开始,将集合c添加到Vector中
public synchronized boolean addAll(int index, Collection<? extends E> c) {
    //modCount++ 统计Vector的修改次数
        modCount++;
        if (index < 0 || index > elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
     //c集合转换成数组
        Object[] a = c.toArray();
     //集合数组长度 扩容使用
        int numNew = a.length;
     //扩容
        ensureCapacityHelper(elementCount + numNew);
     //元素移动个数
        int numMoved = elementCount - index;
        if (numMoved > 0)
       //elementData[]把从index开始的元素移动到 elementData[]从index + numNew 移动的个数numMoved
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
     //把a[]放入elementData[]数组对应的位置
        System.arraycopy(a, 0, elementData, index, numNew);
     //更新实际数组大小
        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();
 }

 //Vector中fromIndex(包括)到toIndex(不包括)的子集
public synchronized List<E> subList(int fromIndex, int toIndex) 
{
 return Collections.synchronizedList(super.subList(fromIndex, toIndex),this);
}

// 从此 List 中移除其索引位于 fromIndex(包括)与 toIndex(不包括)之间的所有元素。  
protected synchronized void removeRange(int fromIndex, int toIndex) 
{
    //modCount++ 统计Vector的修改次数
        modCount++;
    //移动个数 
        int numMoved = elementCount - toIndex;
     //toIndex位置开始整体往前移动到fromIndex位置 也就是将后面的对象移到前面来
        System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);

        // Let gc do its work  原来索引下的元素移走后设为null 由GC机制处理
        int newElementCount = elementCount - (toIndex-fromIndex);
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
}
/*
  将vector实例的状态保存到流(序列化vector)。
  此方法执行同步以确保序列化数据的一致性。
*/
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<E> listIterator(int index) 
{
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
}

//返回默认游标位置为起始位置0的列表迭代器,
public synchronized ListIterator<E> listIterator() 
{
        return new ListItr(0);
}

// 返回一个迭代器
public synchronized Iterator<E> iterator() 
{
        return new Itr();
}

//迭代器默认实现,会出现fail-fast机制
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();
        }
    }
  //列表迭代器
  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 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;
        }
    }
View Code

 

代码用例:

 Vector vector = new Vector();
        vector.add("test1");
        vector.add("test2");
        vector.add("test3");
        //add 添加元素 返回boolean
         boolean v1 = vector.add("zhangsan");
         //addElement 同add方法 无返回值 
         vector.addElement("zhangsan:"+String.valueOf(v1));
         //insertElementAt  根据下标插入元素
         vector.insertElementAt("first--zhangsan", 0);
         System.out.println("元素:"+vector.toString());
         //subList 获得从fromIndex[含]开始--toIndex[不含]结束的元素
        List<String> subList = vector.subList(1, 3);
         System.out.println("截取下标1[含]-3[不含]:"+subList);
         //clone 复制
         Vector vCopy = (Vector) vector.clone();
         System.out.println("vCopy副本:"+vCopy);
         //copyInto 复制到指定的数组中
         Object[] objects = new Object[vCopy.size()];
         vCopy.copyInto(objects);
         String split = "";
         StringBuffer sb = new StringBuffer(); 
         for (Object object : objects) {
            sb.append(split).append(object);
            split = ",";
        }
         System.out.println("---objects:"+sb.toString());
        // add addAll 添加collection集合的区别
         ArrayList list = new ArrayList();
         list.add("alist1");
         list.add("alist2");
         list.add("alist3");
         //addAll 把集合中元素逐个加入
         vector.addAll(list);
         System.out.println("vector addAll:"+vector);
         //add 把集合当做一个元素加入
         vCopy.add(list);
         System.out.println("vCopy add:"+vCopy);
         //
         vector.remove(1);
         System.out.println("移除下标1的元素后:"+vector.toString());
         vector.remove("test2");
         System.out.println("移除元素test2后:"+vector.toString());
         //
         System.out.println("遍历vector");
         System.out.println("向后遍历:");
         ListIterator<String> iterator =  vector.listIterator();
         while (iterator.hasNext()) {
             System.out.println("下标:"+iterator.nextIndex()+"--元素:"+iterator.next());
        }
      
         //向后遍历
         System.out.println("向前遍历:");
         while (iterator.hasPrevious()) {
             System.out.println("下标:"+iterator.previousIndex()+"--元素:"+iterator.previous());
        }

 

 运行结果:

元素:[first--zhangsan, test1, test2, test3, zhangsan, zhangsan:true]
截取下标1[含]-3[不含]:[test1, test2]
vCopy副本:[first--zhangsan, test1, test2, test3, zhangsan, zhangsan:true]
---objects:first--zhangsan,test1,test2,test3,zhangsan,zhangsan:true
vector addAll:[first--zhangsan, test1, test2, test3, zhangsan, zhangsan:true, alist1, alist2, alist3]
vCopy add:[first--zhangsan, test1, test2, test3, zhangsan, zhangsan:true, [alist1, alist2, alist3]]
移除下标1的元素后:[first--zhangsan, test2, test3, zhangsan, zhangsan:true, alist1, alist2, alist3]
移除元素test2后:[first--zhangsan, test3, zhangsan, zhangsan:true, alist1, alist2, alist3]
遍历vector
向后遍历:
下标:0--元素:first--zhangsan
下标:1--元素:test3
下标:2--元素:zhangsan
下标:3--元素:zhangsan:true
下标:4--元素:alist1
下标:5--元素:alist2
下标:6--元素:alist3
向前遍历:
下标:6--元素:alist3
下标:5--元素:alist2
下标:4--元素:alist1
下标:3--元素:zhangsan:true
下标:2--元素:zhangsan
下标:1--元素:test3
下标:0--元素:first--zhangsan

 

 有一点时需要注意的,在使用ListIterator遍历的时候 :一定要先进行由前向后输出,之后才能进行由后向前输出。单独或先执行由后向前输出时是无法输出数据的。

  




 

posted @ 2018-06-12 14:40  smokerBig  阅读(108)  评论(0编辑  收藏  举报