Java集合06--Vector源碼詳解

轉載地址:http://blog.csdn.net/wangxiaotongfan/article/details/51332193

概要

學完ArrayListLinkedList之後,我們接着學習Vector。學習方式還是和之前一樣,先對Vector有個整體認識,然後再學習它的源碼;最後再通過實例來學會使用它。
第1部分 Vector介紹
第2部分 Vector數據結構
第3部分 Vector源碼解析(基於JDK1.6.0_45)
第4部分 Vector遍歷方式
第5部分 Vector示例

第1部分 Vector介紹

Vector簡介

Vector 是矢量隊列,它是JDK1.0版本添加的類。繼承於AbstractList,實現了List, RandomAccess, Cloneable這些接口。
Vector 繼承了AbstractList,實現了List;所以,它是一個隊列,支持相關的添加、刪除、修改、遍歷等功能
Vector 實現了RandmoAccess接口,即提供了隨機訪問功能。RandmoAccess是java中用來被List實現,爲List提供快速訪問功能的。在Vector中,我們即可以通過元素的序號快速獲取元素對象;這就是快速隨機訪問。
Vector 實現了Cloneable接口,即實現clone()函數。它能被克隆。

和ArrayList不同,Vector中的操作是線程安全的

Vector的構造函數

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. Vector共有4個構造函數  
  2. // 默認構造函數  
  3. Vector()  
  4.   
  5. // capacity是Vector的默認容量大小。當由於增加數據導致容量增加時,每次容量會增加一倍。  
  6. Vector(int capacity)  
  7.   
  8. // capacity是Vector的默認容量大小,capacityIncrement是每次Vector容量增加時的增量值。  
  9. Vector(int capacity, int capacityIncrement)  
  10.   
  11. // 創建一個包含collection的Vector  
  12. Vector(Collection<? extends E> collection)  
Vector的API

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. synchronized boolean        add(E object)  
  2.              void           add(int location, E object)  
  3. synchronized boolean        addAll(Collection<? extends E> collection)  
  4. synchronized boolean        addAll(int location, Collection<? extends E> collection)  
  5. synchronized void           addElement(E object)  
  6. synchronized int            capacity()  
  7.              void           clear()  
  8. synchronized Object         clone()  
  9.              boolean        contains(Object object)  
  10. synchronized boolean        containsAll(Collection<?> collection)  
  11. synchronized void           copyInto(Object[] elements)  
  12. synchronized E              elementAt(int location)  
  13.              Enumeration<E> elements()  
  14. synchronized void           ensureCapacity(int minimumCapacity)  
  15. synchronized boolean        equals(Object object)  
  16. synchronized E              firstElement()  
  17.              E              get(int location)  
  18. synchronized int            hashCode()  
  19. synchronized int            indexOf(Object object, int location)  
  20.              int            indexOf(Object object)  
  21. synchronized void           insertElementAt(E object, int location)  
  22. synchronized boolean        isEmpty()  
  23. synchronized E              lastElement()  
  24. synchronized int            lastIndexOf(Object object, int location)  
  25. synchronized int            lastIndexOf(Object object)  
  26. synchronized E              remove(int location)  
  27.              boolean        remove(Object object)  
  28. synchronized boolean        removeAll(Collection<?> collection)  
  29. synchronized void           removeAllElements()  
  30. synchronized boolean        removeElement(Object object)  
  31. synchronized void           removeElementAt(int location)  
  32. synchronized boolean        retainAll(Collection<?> collection)  
  33. synchronized E              set(int location, E object)  
  34. synchronized void           setElementAt(E object, int location)  
  35. synchronized void           setSize(int length)  
  36. synchronized int            size()  
  37. synchronized List<E>        subList(int start, int end)  
  38. synchronized <T> T[]        toArray(T[] contents)  
  39. synchronized Object[]       toArray()  
  40. synchronized String         toString()  
  41. synchronized void           trimToSize()  

第2部分 Vector數據結構

Vector的繼承關係

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. java.lang.Object  
  2.    ↳     java.util.AbstractCollection<E>  
  3.          ↳     java.util.AbstractList<E>  
  4.                ↳     java.util.Vector<E>  
  5.   
  6. public class Vector<E>  
  7.     extends AbstractList<E>  
  8.     implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}  

Vector與Collection關係如下圖


Vector的數據結構和ArrayList差不多,它包含了3個成員變量:elementData , elementCount capacityIncrement

(01) elementData 是"Object[]類型的數組",它保存了添加到Vector中的元素。elementData是個動態數組,如果初始化Vector時,沒指定動態數組的>大小,則使用默認大小10。隨着Vector中元素的增加,Vector的容量也會動態增長,capacityIncrement是與容量增長相關的增長係數,具體的增長方式,請參考源碼分析中的ensureCapacity()函數。

(02) elementCount 是動態數組的實際大小。

(03) capacityIncrement 是動態數組的增長係數。如果在創建Vector時,指定了capacityIncrement的大小;則,每次當Vector中動態數組容量增加時>,增加的大小都是capacityIncrement。

第3部分 Vector源碼解析(基於JDK1.6.0_45)

爲了更瞭解Vector的原理,下面對Vector源碼代碼作出分析

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package java.util;  
  2.   
  3. public class Vector<E>  
  4.     extends AbstractList<E>  
  5.     implements List<E>, RandomAccess, Cloneable, java.io.Serializable  
  6. {  
  7.      
  8.     // 保存Vector中數據的數組  
  9.     protected Object[] elementData;  
  10.   
  11.     // 實際數據的數量  
  12.     protected int elementCount;  
  13.   
  14.     // 容量增長係數  
  15.     protected int capacityIncrement;  
  16.   
  17.     // Vector的序列版本號  
  18.     private static final long serialVersionUID = -2767605614048989439L;  
  19.   
  20.     // Vector構造函數。默認容量是10。  
  21.     public Vector() {  
  22.         this(10);  
  23.     }  
  24.   
  25.     // 指定Vector容量大小的構造函數  
  26.     public Vector(int initialCapacity) {  
  27.         this(initialCapacity, 0);  
  28.     }  
  29.   
  30.     // 指定Vector"容量大小"和"增長係數"的構造函數  
  31.     public Vector(int initialCapacity, int capacityIncrement) {  
  32.         super();  
  33.         if (initialCapacity < 0)  
  34.             throw new IllegalArgumentException("Illegal Capacity: "+  
  35.                                                initialCapacity);  
  36.         // 新建一個數組,數組容量是initialCapacity  
  37.         this.elementData = new Object[initialCapacity];  
  38.         // 設置容量增長係數  
  39.         this.capacityIncrement = capacityIncrement;  
  40.     }  
  41.   
  42.     // 指定集合的Vector構造函數。  
  43.     public Vector(Collection<? extends E> c) {  
  44.         // 獲取“集合(c)”的數組,並將其賦值給elementData  
  45.         elementData = c.toArray();  
  46.         // 設置數組長度  
  47.         elementCount = elementData.length;  
  48.         // c.toArray might (incorrectly) not return Object[] (see 6260652)  
  49.         if (elementData.getClass() != Object[].class)  
  50.             elementData = Arrays.copyOf(elementData, elementCount, Object[].class);  
  51.     }  
  52.   
  53.     // 將數組Vector的全部元素都拷貝到數組anArray中  
  54.     public synchronized void copyInto(Object[] anArray) {  
  55.         System.arraycopy(elementData, 0, anArray, 0, elementCount);  
  56.     }  
  57.   
  58.     // 將當前容量值設爲 =實際元素個數  
  59.     public synchronized void trimToSize() {  
  60.         modCount++;  
  61.         int oldCapacity = elementData.length;  
  62.         if (elementCount < oldCapacity) {  
  63.             elementData = Arrays.copyOf(elementData, elementCount);  
  64.         }  
  65.     }  
  66.   
  67.     // 確認“Vector容量”的幫助函數  
  68.     private void ensureCapacityHelper(int minCapacity) {  
  69.         int oldCapacity = elementData.length;  
  70.         // 當Vector的容量不足以容納當前的全部元素,增加容量大小。  
  71.         // 若 容量增量係數>0(即capacityIncrement>0),則將容量增大當capacityIncrement  
  72.         // 否則,將容量增大一倍。  
  73.         if (minCapacity > oldCapacity) {  
  74.             Object[] oldData = elementData;  
  75.             int newCapacity = (capacityIncrement > 0) ?  
  76.                 (oldCapacity + capacityIncrement) : (oldCapacity * 2);  
  77.             if (newCapacity < minCapacity) {  
  78.                 newCapacity = minCapacity;  
  79.             }  
  80.             elementData = Arrays.copyOf(elementData, newCapacity);  
  81.         }  
  82.     }  
  83.   
  84.     // 確定Vector的容量。  
  85.     public synchronized void ensureCapacity(int minCapacity) {  
  86.         // 將Vector的改變統計數+1  
  87.         modCount++;  
  88.         ensureCapacityHelper(minCapacity);  
  89.     }  
  90.   
  91.     // 設置容量值爲 newSize  
  92.     public synchronized void setSize(int newSize) {  
  93.         modCount++;  
  94.         if (newSize > elementCount) {  
  95.             // 若 "newSize 大於 Vector容量",則調整Vector的大小。  
  96.             ensureCapacityHelper(newSize);  
  97.         } else {  
  98.             // 若 "newSize 小於/等於 Vector容量",則將newSize位置開始的元素都設置爲null  
  99.             for (int i = newSize ; i < elementCount ; i++) {  
  100.                 elementData[i] = null;  
  101.             }  
  102.         }  
  103.         elementCount = newSize;  
  104.     }  
  105.   
  106.     // 返回“Vector的總的容量”  
  107.     public synchronized int capacity() {  
  108.         return elementData.length;  
  109.     }  
  110.   
  111.     // 返回“Vector的實際大小”,即Vector中元素個數  
  112.     public synchronized int size() {  
  113.         return elementCount;  
  114.     }  
  115.   
  116.     // 判斷Vector是否爲空  
  117.     public synchronized boolean isEmpty() {  
  118.         return elementCount == 0;  
  119.     }  
  120.   
  121.     // 返回“Vector中全部元素對應的Enumeration”  
  122.     public Enumeration<E> elements() {  
  123.         // 通過匿名類實現Enumeration  
  124.         return new Enumeration<E>() {  
  125.             int count = 0;  
  126.   
  127.             // 是否存在下一個元素  
  128.             public boolean hasMoreElements() {  
  129.                 return count < elementCount;  
  130.             }  
  131.   
  132.             // 獲取下一個元素  
  133.             public E nextElement() {  
  134.                 synchronized (Vector.this) {  
  135.                     if (count < elementCount) {  
  136.                         return (E)elementData[count++];  
  137.                     }  
  138.                 }  
  139.                 throw new NoSuchElementException("Vector Enumeration");  
  140.             }  
  141.         };  
  142.     }  
  143.   
  144.     // 返回Vector中是否包含對象(o)  
  145.     public boolean contains(Object o) {  
  146.         return indexOf(o, 0) >= 0;  
  147.     }  
  148.   
  149.   
  150.     // 從index位置開始向後查找元素(o)。  
  151.     // 若找到,則返回元素的索引值;否則,返回-1  
  152.     public synchronized int indexOf(Object o, int index) {  
  153.         if (o == null) {  
  154.             // 若查找元素爲null,則正向找出null元素,並返回它對應的序號  
  155.             for (int i = index ; i < elementCount ; i++)  
  156.             if (elementData[i]==null)  
  157.                 return i;  
  158.         } else {  
  159.             // 若查找元素不爲null,則正向找出該元素,並返回它對應的序號  
  160.             for (int i = index ; i < elementCount ; i++)  
  161.             if (o.equals(elementData[i]))  
  162.                 return i;  
  163.         }  
  164.         return -1;  
  165.     }  
  166.   
  167.     // 查找並返回元素(o)在Vector中的索引值  
  168.     public int indexOf(Object o) {  
  169.         return indexOf(o, 0);  
  170.     }  
  171.   
  172.     // 從後向前查找元素(o)。並返回元素的索引  
  173.     public synchronized int lastIndexOf(Object o) {  
  174.         return lastIndexOf(o, elementCount-1);  
  175.     }  
  176.   
  177.     // 從後向前查找元素(o)。開始位置是從前向後的第index個數;  
  178.     // 若找到,則返回元素的“索引值”;否則,返回-1。  
  179.     public synchronized int lastIndexOf(Object o, int index) {  
  180.         if (index >= elementCount)  
  181.             throw new IndexOutOfBoundsException(index + " >= "+ elementCount);  
  182.   
  183.         if (o == null) {  
  184.             // 若查找元素爲null,則反向找出null元素,並返回它對應的序號  
  185.             for (int i = index; i >= 0; i--)  
  186.             if (elementData[i]==null)  
  187.                 return i;  
  188.         } else {  
  189.             // 若查找元素不爲null,則反向找出該元素,並返回它對應的序號  
  190.             for (int i = index; i >= 0; i--)  
  191.             if (o.equals(elementData[i]))  
  192.                 return i;  
  193.         }  
  194.         return -1;  
  195.     }  
  196.   
  197.     // 返回Vector中index位置的元素。  
  198.     // 若index月結,則拋出異常  
  199.     public synchronized E elementAt(int index) {  
  200.         if (index >= elementCount) {  
  201.             throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);  
  202.         }  
  203.   
  204.         return (E)elementData[index];  
  205.     }  
  206.   
  207.     // 獲取Vector中的第一個元素。  
  208.     // 若失敗,則拋出異常!  
  209.     public synchronized E firstElement() {  
  210.         if (elementCount == 0) {  
  211.             throw new NoSuchElementException();  
  212.         }  
  213.         return (E)elementData[0];  
  214.     }  
  215.   
  216.     // 獲取Vector中的最後一個元素。  
  217.     // 若失敗,則拋出異常!  
  218.     public synchronized E lastElement() {  
  219.         if (elementCount == 0) {  
  220.             throw new NoSuchElementException();  
  221.         }  
  222.         return (E)elementData[elementCount - 1];  
  223.     }  
  224.   
  225.     // 設置index位置的元素值爲obj  
  226.     public synchronized void setElementAt(E obj, int index) {  
  227.         if (index >= elementCount) {  
  228.             throw new ArrayIndexOutOfBoundsException(index + " >= " +  
  229.                                  elementCount);  
  230.         }  
  231.         elementData[index] = obj;  
  232.     }  
  233.   
  234.     // 刪除index位置的元素  
  235.     public synchronized void removeElementAt(int index) {  
  236.         modCount++;  
  237.         if (index >= elementCount) {  
  238.             throw new ArrayIndexOutOfBoundsException(index + " >= " +  
  239.                                  elementCount);  
  240.         } else if (index < 0) {  
  241.             throw new ArrayIndexOutOfBoundsException(index);  
  242.         }  
  243.   
  244.         int j = elementCount - index - 1;  
  245.         if (j > 0) {  
  246.             System.arraycopy(elementData, index + 1, elementData, index, j);  
  247.         }  
  248.         elementCount--;  
  249.         elementData[elementCount] = null/* to let gc do its work */  
  250.     }  
  251.   
  252.     // 在index位置處插入元素(obj)  
  253.     public synchronized void insertElementAt(E obj, int index) {  
  254.         modCount++;  
  255.         if (index > elementCount) {  
  256.             throw new ArrayIndexOutOfBoundsException(index  
  257.                                  + " > " + elementCount);  
  258.         }  
  259.         ensureCapacityHelper(elementCount + 1);  
  260.         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);  
  261.         elementData[index] = obj;  
  262.         elementCount++;  
  263.     }  
  264.   
  265.     // 將“元素obj”添加到Vector末尾  
  266.     public synchronized void addElement(E obj) {  
  267.         modCount++;  
  268.         ensureCapacityHelper(elementCount + 1);  
  269.         elementData[elementCount++] = obj;  
  270.     }  
  271.   
  272.     // 在Vector中查找並刪除元素obj。  
  273.     // 成功的話,返回true;否則,返回false。  
  274.     public synchronized boolean removeElement(Object obj) {  
  275.         modCount++;  
  276.         int i = indexOf(obj);  
  277.         if (i >= 0) {  
  278.             removeElementAt(i);  
  279.             return true;  
  280.         }  
  281.         return false;  
  282.     }  
  283.   
  284.     // 刪除Vector中的全部元素  
  285.     public synchronized void removeAllElements() {  
  286.         modCount++;  
  287.         // 將Vector中的全部元素設爲null  
  288.         for (int i = 0; i < elementCount; i++)  
  289.             elementData[i] = null;  
  290.   
  291.         elementCount = 0;  
  292.     }  
  293.   
  294.     // 克隆函數  
  295.     public synchronized Object clone() {  
  296.         try {  
  297.             Vector<E> v = (Vector<E>) super.clone();  
  298.             // 將當前Vector的全部元素拷貝到v中  
  299.             v.elementData = Arrays.copyOf(elementData, elementCount);  
  300.             v.modCount = 0;  
  301.             return v;  
  302.         } catch (CloneNotSupportedException e) {  
  303.             // this shouldn't happen, since we are Cloneable  
  304.             throw new InternalError();  
  305.         }  
  306.     }  
  307.   
  308.     // 返回Object數組  
  309.     public synchronized Object[] toArray() {  
  310.         return Arrays.copyOf(elementData, elementCount);  
  311.     }  
  312.   
  313.     // 返回Vector的模板數組。所謂模板數組,即可以將T設爲任意的數據類型  
  314.     public synchronized <T> T[] toArray(T[] a) {  
  315.         // 若數組a的大小 < Vector的元素個數;  
  316.         // 則新建一個T[]數組,數組大小是“Vector的元素個數”,並將“Vector”全部拷貝到新數組中  
  317.         if (a.length < elementCount)  
  318.             return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());  
  319.   
  320.         // 若數組a的大小 >= Vector的元素個數;  
  321.         // 則將Vector的全部元素都拷貝到數組a中。  
  322.     System.arraycopy(elementData, 0, a, 0, elementCount);  
  323.   
  324.         if (a.length > elementCount)  
  325.             a[elementCount] = null;  
  326.   
  327.         return a;  
  328.     }  
  329.   
  330.     // 獲取index位置的元素  
  331.     public synchronized E get(int index) {  
  332.         if (index >= elementCount)  
  333.             throw new ArrayIndexOutOfBoundsException(index);  
  334.   
  335.         return (E)elementData[index];  
  336.     }  
  337.   
  338.     // 設置index位置的值爲element。並返回index位置的原始值  
  339.     public synchronized E set(int index, E element) {  
  340.         if (index >= elementCount)  
  341.             throw new ArrayIndexOutOfBoundsException(index);  
  342.   
  343.         Object oldValue = elementData[index];  
  344.         elementData[index] = element;  
  345.         return (E)oldValue;  
  346.     }  
  347.   
  348.     // 將“元素e”添加到Vector最後。  
  349.     public synchronized boolean add(E e) {  
  350.         modCount++;  
  351.         ensureCapacityHelper(elementCount + 1);  
  352.         elementData[elementCount++] = e;  
  353.         return true;  
  354.     }  
  355.   
  356.     // 刪除Vector中的元素o  
  357.     public boolean remove(Object o) {  
  358.         return removeElement(o);  
  359.     }  
  360.   
  361.     // 在index位置添加元素element  
  362.     public void add(int index, E element) {  
  363.         insertElementAt(element, index);  
  364.     }  
  365.   
  366.     // 刪除index位置的元素,並返回index位置的原始值  
  367.     public synchronized E remove(int index) {  
  368.         modCount++;  
  369.         if (index >= elementCount)  
  370.             throw new ArrayIndexOutOfBoundsException(index);  
  371.         Object oldValue = elementData[index];  
  372.   
  373.         int numMoved = elementCount - index - 1;  
  374.         if (numMoved > 0)  
  375.             System.arraycopy(elementData, index+1, elementData, index,  
  376.                      numMoved);  
  377.         elementData[--elementCount] = null// Let gc do its work  
  378.   
  379.         return (E)oldValue;  
  380.     }  
  381.   
  382.     // 清空Vector  
  383.     public void clear() {  
  384.         removeAllElements();  
  385.     }  
  386.   
  387.     // 返回Vector是否包含集合c  
  388.     public synchronized boolean containsAll(Collection<?> c) {  
  389.         return super.containsAll(c);  
  390.     }  
  391.   
  392.     // 將集合c添加到Vector中  
  393.     public synchronized boolean addAll(Collection<? extends E> c) {  
  394.         modCount++;  
  395.         Object[] a = c.toArray();  
  396.         int numNew = a.length;  
  397.         ensureCapacityHelper(elementCount + numNew);  
  398.         // 將集合c的全部元素拷貝到數組elementData中  
  399.         System.arraycopy(a, 0, elementData, elementCount, numNew);  
  400.         elementCount += numNew;  
  401.         return numNew != 0;  
  402.     }  
  403.   
  404.     // 刪除集合c的全部元素  
  405.     public synchronized boolean removeAll(Collection<?> c) {  
  406.         return super.removeAll(c);  
  407.     }  
  408.   
  409.     // 刪除“非集合c中的元素”  
  410.     public synchronized boolean retainAll(Collection<?> c)  {  
  411.         return super.retainAll(c);  
  412.     }  
  413.   
  414.     // 從index位置開始,將集合c添加到Vector中  
  415.     public synchronized boolean addAll(int index, Collection<? extends E> c) {  
  416.         modCount++;  
  417.         if (index < 0 || index > elementCount)  
  418.             throw new ArrayIndexOutOfBoundsException(index);  
  419.   
  420.         Object[] a = c.toArray();  
  421.         int numNew = a.length;  
  422.         ensureCapacityHelper(elementCount + numNew);  
  423.   
  424.         int numMoved = elementCount - index;  
  425.         if (numMoved > 0)  
  426.         System.arraycopy(elementData, index, elementData, index + numNew, numMoved);  
  427.   
  428.         System.arraycopy(a, 0, elementData, index, numNew);  
  429.         elementCount += numNew;  
  430.         return numNew != 0;  
  431.     }  
  432.   
  433.     // 返回兩個對象是否相等  
  434.     public synchronized boolean equals(Object o) {  
  435.         return super.equals(o);  
  436.     }  
  437.   
  438.     // 計算哈希值  
  439.     public synchronized int hashCode() {  
  440.         return super.hashCode();  
  441.     }  
  442.   
  443.     // 調用父類的toString()  
  444.     public synchronized String toString() {  
  445.         return super.toString();  
  446.     }  
  447.   
  448.     // 獲取Vector中fromIndex(包括)到toIndex(不包括)的子集  
  449.     public synchronized List<E> subList(int fromIndex, int toIndex) {  
  450.         return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);  
  451.     }  
  452.   
  453.     // 刪除Vector中fromIndex到toIndex的元素  
  454.     protected synchronized void removeRange(int fromIndex, int toIndex) {  
  455.         modCount++;  
  456.         int numMoved = elementCount - toIndex;  
  457.         System.arraycopy(elementData, toIndex, elementData, fromIndex,  
  458.                          numMoved);  
  459.   
  460.         // Let gc do its work  
  461.         int newElementCount = elementCount - (toIndex-fromIndex);  
  462.         while (elementCount != newElementCount)  
  463.             elementData[--elementCount] = null;  
  464.     }  
  465.   
  466.     // java.io.Serializable的寫入函數  
  467.     private synchronized void writeObject(java.io.ObjectOutputStream s)  
  468.         throws java.io.IOException {  
  469.         s.defaultWriteObject();  
  470.     }  
  471. }  

總結
(01) Vector實際上是通過一個數組去保存數據的。當我們構造Vecotr時;若使用默認構造函數,則Vector的默認容量大小是10
(02) 當Vector容量不足以容納全部元素時,Vector的容量會增加。若容量增加係數 >0,則將容量的值增加“容量增加係數”;否則,將容量大小增加一倍。
(03) Vector的克隆函數,即是將全部元素克隆到一個數組中。

第4部分 Vector遍歷方式

Vector支持4種遍歷方式。建議使用下面的第二種去遍歷Vector,因爲效率問題。

(01) 第一種,通過迭代器遍歷。即通過Iterator去遍歷。

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. Integer value = null;  
  2. int size = vec.size();  
  3. for (int i=0; i<size; i++) {  
  4.     value = (Integer)vec.get(i);          
  5. }  

(02) 第二種,隨機訪問,通過索引值去遍歷。
由於Vector實現了RandomAccess接口,它支持通過索引值去隨機訪問元素。

  1. Integer value = null;  
  2. int size = vec.size();  
  3. for (int i=0; i<size; i++) {  
  4.     value = (Integer)vec.get(i);          
  5. }  

(03) 第三種,另一種for循環。如下:

  1. Integer value = null;  
  2. for (Integer integ:vec) {  
  3.     value = integ;  
  4. }  

(04) 第四種,Enumeration遍歷。如下: 

  1. Integer value = null;  
  2. Enumeration enu = vec.elements();  
  3. while (enu.hasMoreElements()) {  
  4.     value = (Integer)enu.nextElement();  
  5. }  
代碼測試

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. import java.util.*;  
  2.   
  3. /* 
  4.  * @desc Vector遍歷方式和效率的測試程序。 
  5.  * 
  6.  * @author skywang 
  7.  */  
  8. public class VectorRandomAccessTest {  
  9.   
  10.     public static void main(String[] args) {  
  11.         Vector vec= new Vector();  
  12.         for (int i=0; i<100000; i++)  
  13.             vec.add(i);  
  14.         iteratorThroughRandomAccess(vec) ;  
  15.         iteratorThroughIterator(vec) ;  
  16.         iteratorThroughFor2(vec) ;  
  17.         iteratorThroughEnumeration(vec) ;  
  18.       
  19.     }  
  20.   
  21.     private static void isRandomAccessSupported(List list) {  
  22.         if (list instanceof RandomAccess) {  
  23.             System.out.println("RandomAccess implemented!");  
  24.         } else {  
  25.             System.out.println("RandomAccess not implemented!");  
  26.         }  
  27.   
  28.     }  
  29.   
  30.     public static void iteratorThroughRandomAccess(List list) {  
  31.   
  32.         long startTime;  
  33.         long endTime;  
  34.         startTime = System.currentTimeMillis();  
  35.         for (int i=0; i<list.size(); i++) {  
  36.             list.get(i);  
  37.         }  
  38.         endTime = System.currentTimeMillis();  
  39.         long interval = endTime - startTime;  
  40.         System.out.println("iteratorThroughRandomAccess:" + interval+" ms");  
  41.     }  
  42.   
  43.     public static void iteratorThroughIterator(List list) {  
  44.   
  45.         long startTime;  
  46.         long endTime;  
  47.         startTime = System.currentTimeMillis();  
  48.         for(Iterator iter = list.iterator(); iter.hasNext(); ) {  
  49.             iter.next();  
  50.         }  
  51.         endTime = System.currentTimeMillis();  
  52.         long interval = endTime - startTime;  
  53.         System.out.println("iteratorThroughIterator:" + interval+" ms");  
  54.     }  
  55.   
  56.   
  57.     public static void iteratorThroughFor2(List list) {  
  58.   
  59.         long startTime;  
  60.         long endTime;  
  61.         startTime = System.currentTimeMillis();  
  62.         for(Object obj:list)  
  63.             ;  
  64.         endTime = System.currentTimeMillis();  
  65.         long interval = endTime - startTime;  
  66.         System.out.println("iteratorThroughFor2:" + interval+" ms");  
  67.     }  
  68.   
  69.     public static void iteratorThroughEnumeration(Vector vec) {  
  70.   
  71.         long startTime;  
  72.         long endTime;  
  73.         startTime = System.currentTimeMillis();  
  74.         for(Enumeration enu = vec.elements(); enu.hasMoreElements(); ) {  
  75.             enu.nextElement();  
  76.         }  
  77.         endTime = System.currentTimeMillis();  
  78.         long interval = endTime - startTime;  
  79.         System.out.println("iteratorThroughEnumeration:" + interval+" ms");  
  80.     }  
  81. }  

運行結果

  1. iteratorThroughRandomAccess:6 ms  
  2. iteratorThroughIterator:9 ms  
  3. iteratorThroughFor2:8 ms  
  4. iteratorThroughEnumeration:7 ms  

總結:遍歷Vector,使用索引的隨機訪問方式最快,使用迭代器最慢。

第5部分 Vector示例

下面通過示例學習如何使用Vector

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. import java.util.Vector;  
  2. import java.util.List;  
  3. import java.util.Iterator;  
  4. import java.util.Enumeration;  
  5.   
  6. /** 
  7.  * @desc Vector測試函數:遍歷Vector和常用API  
  8.  * 
  9.  * @author skywang 
  10.  */  
  11. public class VectorTest {  
  12.     public static void main(String[] args) {  
  13.         // 新建Vector  
  14.         Vector vec = new Vector();  
  15.               
  16.         // 添加元素  
  17.         vec.add("1");  
  18.         vec.add("2");  
  19.         vec.add("3");  
  20.         vec.add("4");  
  21.         vec.add("5");  
  22.   
  23.         // 設置第一個元素爲100  
  24.         vec.set(0"100");  
  25.         // 將“500”插入到第3個位置  
  26.         vec.add(2"300");  
  27.         System.out.println("vec:"+vec);  
  28.   
  29.         // (順序查找)獲取100的索引  
  30.         System.out.println("vec.indexOf(100):"+vec.indexOf("100"));  
  31.         // (倒序查找)獲取100的索引  
  32.         System.out.println("vec.lastIndexOf(100):"+vec.lastIndexOf("100"));  
  33.         // 獲取第一個元素  
  34.         System.out.println("vec.firstElement():"+vec.firstElement());  
  35.         // 獲取第3個元素  
  36.         System.out.println("vec.elementAt(2):"+vec.elementAt(2));  
  37.         // 獲取最後一個元素  
  38.         System.out.println("vec.lastElement():"+vec.lastElement());  
  39.   
  40.         // 獲取Vector的大小  
  41.         System.out.println("size:"+vec.size());  
  42.         // 獲取Vector的總的容量  
  43.         System.out.println("capacity:"+vec.capacity());  
  44.   
  45.         // 獲取vector的“第2”到“第4”個元素  
  46.         System.out.println("vec 2 to 4:"+vec.subList(14));  
  47.   
  48.         // 通過Enumeration遍歷Vector  
  49.         Enumeration enu = vec.elements();  
  50.         while(enu.hasMoreElements())  
  51.             System.out.println("nextElement():"+enu.nextElement());  
  52.               
  53.         Vector retainVec = new Vector();  
  54.         retainVec.add("100");  
  55.         retainVec.add("300");  
  56.         // 獲取“vec”中包含在“retainVec中的元素”的集合  
  57.         System.out.println("vec.retain():"+vec.retainAll(retainVec));  
  58.         System.out.println("vec:"+vec);  
  59.               
  60.         // 獲取vec對應的String數組  
  61.         String[] arr = (String[]) vec.toArray(new String[0]);  
  62.         for (String str:arr)  
  63.             System.out.println("str:"+str);  
  64.   
  65.         // 清空Vector。clear()和removeAllElements()一樣!  
  66.         vec.clear();  
  67. //        vec.removeAllElements();  
  68.   
  69.         // 判斷Vector是否爲空  
  70.         System.out.println("vec.isEmpty():"+vec.isEmpty());  
  71.     }     
  72. }  
運行結果

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. vec:[1002300345]  
  2. vec.indexOf(100):0  
  3. vec.lastIndexOf(100):0  
  4. vec.firstElement():100  
  5. vec.elementAt(2):300  
  6. vec.lastElement():5  
  7. size:6  
  8. capacity:10  
  9. vec 2 to 4:[23003]  
  10. nextElement():100  
  11. nextElement():2  
  12. nextElement():300  
  13. nextElement():3  
  14. nextElement():4  
  15. nextElement():5  
  16. vec.retain():true  
  17. vec:[100300]  
  18. str:100  
  19. str:300  
  20. vec.isEmpty():true  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章