【Java集合类源码分析】Vector源码分析
来源:互联网 发布:cura切片软件 编辑:程序博客网 时间:2024/05/16 18:24
【Java集合类源码分析】Vector源码分析
一、Vector简介
Vector是JDK1.0引入的,基于动态数组实现的,其容量能够动态增长。
public class Vector extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable
Vector继承了AbstarctList抽象类,实现了List接口。
Vector实现了RandomAccess接口,支持快速随机访问(通过下标序号进行快速访问);实现了Cloneable接口,支持克隆;实现了Serializable接口,支持序列化,能够通过序列化传输。
Vector线程安全(实现方法加上了synchronized同步关键字),可在多线程环境下使用。
二、Vector源码分析
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ /** * Vector基于该数组实现,用该数组存储元素 * @serial */ protected Object[] elementData; /** * 实际元素的个数 * @serial */ protected int elementCount; /** * 容量增长系数(当Vector的大小大于其容量时,其容量自动增加的量) * 如果容量增量小于或等于零,则Vector每次需要增长时其容量将加倍 * @serial */ protected int capacityIncrement; /** 序列版本号 */ private static final long serialVersionUID = -2767605614048989439L; /** * 构造具有指定的初始容量和容量增量的空Vector。 * @param initialCapacity Vector的初始容量 * @param capacityIncrement 当Vector溢出时容量增加的量 */ public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } /** * 构造具有指定初始容量并且其容量增量等于0的空Vector */ public Vector(int initialCapacity) { this(initialCapacity, 0); } /** * 构造一个空的Vector,使其内部的数据数组大小为10,其标准容量增量为0 */ public Vector() { this(10); } /** * 构造一个包含指定集合元素的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的全部元素拷贝到指定的数组中。 */ public synchronized void copyInto(Object[] anArray) { System.arraycopy(elementData, 0, anArray, 0, elementCount); } /** * 将当前容量值设为实际元素个数 * 如果该Vector的容量大于其当前大小,返回一个新数组给elementData,将容量更改为等于大小。 * 可以使用此操作来最小化向量容量以节省空间。 */ public synchronized void trimToSize() { modCount++; int oldCapacity = elementData.length; if (elementCount < oldCapacity) { elementData = Arrays.copyOf(elementData, elementCount); } } /** * 如果需要,增加此向量的容量,以确保它可以至少容纳最小容量参数指定的元素数 * @param minCapacity 所需的最小容量 */ public synchronized void ensureCapacity(int minCapacity) { if (minCapacity > 0) { modCount++; ensureCapacityHelper(minCapacity); } } /** * 这实现了ensureCapacity的非同步语义。 * 该类中的同步方法可以内部调用此方法来确保容量,而不会导致额外同步的成本。 */ private void ensureCapacityHelper(int minCapacity) { // overflow-conscious code //当所需容量>Vector容量,进行扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); } /** * 数组可被分配的最大容量。当需要的数组尺寸超过VM的限制时,可能导致OutOfMemoryError */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; //当capacityIncrement>0,则容量增加capacityIncrement,否则,容量将增加一倍 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 newSize 新大小 */ public synchronized void setSize(int newSize) { modCount++; if (newSize > elementCount) { //若新容量>当前Vector容量,则进行扩容 ensureCapacityHelper(newSize); } else { //若新容量<=当前Vector容量,则将newSize位置开始的元素都设置为null for (int i = newSize ; i < elementCount ; i++) { elementData[i] = null; } } elementCount = newSize; } /** * 返回此Vector当前的容量(即其内部数组的长度) */ public synchronized int capacity() { return elementData.length; } /** * 返回此Vector实际大小(即Vector中元素个数) */ public synchronized int size() { return elementCount; } /** * 判断Vector是否为空 */ public synchronized boolean isEmpty() { return elementCount == 0; } /** * 返回Vector中全部元素对应的Enumeration */ 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"); } }; } /** * 如果此Vector中包含指定的元素,则返回true */ public boolean contains(Object o) { return indexOf(o, 0) >= 0; } /** * 返回此Vector中指定元素第一次出现的索引(从前向后搜索) */ public int indexOf(Object o) { return indexOf(o, 0); } /** * 返回此Vector中指定元素第一次出现的索引 * @param o 要查找的元素 * @param index 从index位置开始从前向后查找 */ public synchronized int indexOf(Object o, int index) { if (o == null) { ////说明Vector允许元素为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; } /** * 返回此Vector中指定元素最后一次出现的索引(从后向前搜索) */ public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); } /** * 返回此Vector中指定元素最后一次出现的索引 * @param o 要查找的元素 * @param index 从index位置开始从后向前查找 */ 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); } /** * 返回此Vector的第一个元素(即索引0的元素) */ public synchronized E firstElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(0); } /** * 返回此Vector的最后一个元素 */ public synchronized E lastElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(elementCount - 1); } /** * 将此Vector的指定索引处的元素设置为指定的对象 */ 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++; } /** * 将指定元素添加到此Vector的末尾, */ public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; } /** * 从此Vector中删除第一个出现的参数 */ public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; } /** * 从此Vector中删除所有元素,并将其大小设置为零 */ public synchronized void removeAllElements() { modCount++; // Let gc do its work for (int i = 0; i < elementCount; i++) elementData[i] = null; elementCount = 0; } /** * 返回此Vector的克隆。 该副本将包含对内部数据数组的克隆的引用,而不是引用此Vector的原始内部数据数组(即浅拷贝) */ 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); } } /** * 返回一个包含此Vector中所有元素的数组 */ public synchronized Object[] toArray() { return Arrays.copyOf(elementData, elementCount); } /** * 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型 */ @SuppressWarnings("unchecked") 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; } // 位置访问操作 @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** * 返回此Vector中指定位置的元素 */ public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } /** * 用指定的元素替换此Vector中指定位置的元素,并返回替换前的元素 */ public synchronized E set(int index, E element) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * 将指定的元素追加到此Vector的末尾 */ public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } /** * 删除此Vector中第一次出现的指定元素 */ public boolean remove(Object o) { return removeElement(o); } /** * 在此Vector中的指定位置插入指定的元素 */ public void add(int index, E element) { insertElementAt(element, index); } /** * 删除此Vector中指定位置的元素,并返回删除的元素 */ 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; } /** * 从此Vector中删除所有元素 */ public void clear() { removeAllElements(); } // Bulk Operations /** * 如果此Vector包含指定集合中的所有元素,则返回true */ public synchronized boolean containsAll(Collection<?> c) { return super.containsAll(c); } /** * 将指定集合中的所有元素追加到此Vector的末尾 */ 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; } /** * 从此Vector中删除指定集合中包含的所有元素 */ public synchronized boolean removeAll(Collection<?> c) { return super.removeAll(c); } /** * 仅保留此向Vector中包含在指定集合中的元素 */ public synchronized boolean retainAll(Collection<?> c) { return super.retainAll(c); } /** * 将指定集合中的所有元素插入到此Vector中的指定位置 */ 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 equals(Object o) { return super.equals(o); } /** * 返回此Vector的哈希码值 */ public synchronized int hashCode() { return super.hashCode(); } /** * 返回此Vector的字符串表示形式,其中包含每个元素的String表示 */ 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); } /** * 删除此Vector中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; } /** * 将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(); }}
三、Vector遍历方式
1、通过迭代器Iterator遍历
Iterator iter = vector.iterator();while (iter.hasNext()) { System.out.println(iter.next());}
2、通过迭代器ListIterator遍历
ListIterator lIter = vector.listIterator();//顺向遍历while (lIter.hasNext()) { System.out.println(lIter.next());}//逆向遍历while (lIter.hasPrevious()) { System.out.println(lIter.previous());}
3、随机访问,通过索引值遍历(由于实现了RandomAccess接口)
for (int i = 0; i < vector.size; i++) { System.out.println(vector.get(i)); }
4、foreach循环遍历
for (String str : vector) { System.out.println(str); }
5、Enumeration遍历
Enumeration enu = vector.elements();while (enu.hasMoreElements()) { System.out.println(enu.nextElement());}
四、总结
1、扩容机制:与ArrayList相同,Vector在每次增加元素时,都要调用ensureCapacityHelper()方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就先看构造方法中传入的容量增长量参数capacityIncrement是否为0,如果不为0,就设置新的容量为当前容量加上容量增长量,如果为0,就设置新的容量为旧的容量的2倍,如果设置后的新容量还不够,则直接将新容量设置为传入的参数(也就是所需的容量),而后同样用Arrays.copyof()方法将元素拷贝到新的数组。
2、几乎每个方法上都增加了synchronized 关键字来实现线程间的同步,来保证线程安全。
3、在查找给定元素索引值、删除指定元素等方法中,源码都将该元素的值分为null和不为null两种情况处理,Vector中允许元素为null。
4、Vector不仅支持Iterator和ListIterator迭代器遍历而且支持Enumeration遍历。
- 【Java集合类源码分析】Vector源码分析
- Java集合之Vector源码分析
- Java Vector 源码分析
- 《Java源码分析》:Vector
- 《Java源码分析》:Vector
- 【Java源码分析】Vector源码分析
- java 集合类源码分析
- java集合源码分析
- Java集合源码分析
- Java集合:Vector使用详解及源码分析
- Java 集合框架源码分析(五)——Vector
- java 中的集合(四) Vector源码分析
- Java数据结构源码分析-Vector
- 【Java集合类源码分析】ArrayList源码分析
- 【Java集合类源码分析】LinkedList源码分析
- 【Java集合类源码分析】HashMap源码分析一
- 【Java集合类源码分析】HashMap源码分析二
- 【Java集合类源码分析】LinkedHashMap源码分析
- ZCMU 1098 查找元素
- React Native打包
- 在阿里云上部署Laravel应用
- 【学习笔记09】java面向对象-final、抽象类
- xlistview--狸菇凉_
- 【Java集合类源码分析】Vector源码分析
- Linux-权限知识
- ROI_PAC--use_rsc.pl使用说明
- Margin Convention
- 西电捷通:面向安全协议套件的基线生成方法
- K-means以及K-Means++
- Linux下修改Mysql的用户(root)的密码
- c++第5次上机实验:数组分离
- Android AIDL的使用与理解