Java集合源代码剖析(一)【集合框架概述、ArrayList、LinkedList、Vector】

Java集合框架概述


Java集合工具包位于Java.util包下。包括了非常多经常使用的数据结构,如数组、链表、栈、队列、集合、哈希表等。学习Java集合框架下大致能够分为例如以下五个部分:List列表、Set集合、Map映射、迭代器(Iterator、Enumeration)、工具类(Arrays、Collections)。

    Java集合类的总体框架例如以下:

 

    从上图中能够看出,集合类主要分为两大类:Collection和Map。

    Collection是List、Set等集合高度抽象出来的接口,它包括了这些集合的基本操作。它主要又分为两大部分:List和Set。

    List接口通常表示一个列表(数组、队列、链表、栈等),当中的元素能够反复。经常使用实现类为ArrayList和LinkedList,另外还有不经常使用的Vector。另外,LinkedList还是实现了Queue接口。因此也能够作为队列使用。

    Set接口通常表示一个集合。当中的元素不同意反复(通过hashcode和equals函数保证),经常使用实现类有HashSet和TreeSet,HashSet是通过Map中的HashMap实现的。而TreeSet是通过Map中的TreeMap实现的。

另外。TreeSet还实现了SortedSet接口,因此是有序的集合(集合中的元素要实现Comparable接口。并覆写Compartor函数才行)。

    我们看到,抽象类AbstractCollection、AbstractList和AbstractSet分别实现了Collection、List和Set接口,这就是在Java集合框架中用的非常多的适配器设计模式。用这些抽象类去实现接口,在抽象类中实现接口中的若干或所有方法,这样以下的一些类仅仅需直接继承该抽象类。并实现自己须要的方法就可以。而不用实现接口中的所有抽象方法。

    Map是一个映射接口。当中的每一个元素都是一个key-value键值对,相同抽象类AbstractMap通过适配器模式实现了Map接口中的大部分函数,TreeMap、HashMap、WeakHashMap等实现类都通过继承AbstractMap来实现,另外,不经常使用的HashTable直接实现了Map接口,它和Vector都是JDK1.0就引入的集合类。

    Iterator是遍历集合的迭代器(不能遍历Map,仅仅用来遍历Collection)。Collection的实现类都实现了iterator()函数,它返回一个Iterator对象。用来遍历集合,ListIterator则专门用来遍历List。而Enumeration则是JDK1.0时引入的,作用与Iterator相同,但它的功能比Iterator要少,它仅仅能再Hashtable、Vector和Stack中使用。

    Arrays和Collections是用来操作数组、集合的两个工具类。比如在ArrayList和Vector中大量调用了Arrays.Copyof()方法,而Collections中有非常多静态方法能够返回各集合类的synchronized版本号,即线程安全的版本号,当然了,假设要用线程安全的结合类,首选Concurrent并发包下的相应的集合类。


ArrayList源代码剖析


ArrayList简单介绍

    ArrayList是基于数组实现的。是一个动态数组。其容量能自己主动增长,相似于C语言中的动态申请内存,动态增长内存。

    ArrayList不是线程安全的,仅仅能用在单线程环境下,多线程环境下能够考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也能够使用concurrent并发包下的CopyOnWriteArrayList类。

    ArrayList实现了Serializable接口,因此它支持序列化。能够通过序列化传输,实现了RandomAccess接口。支持高速随机訪问。实际上就是通过下标序号进行高速訪问,实现了Cloneable接口,能被克隆。


ArrayList源代码剖析

    ArrayList的源代码例如以下(加入了比較具体的凝视):

  1. package java.util;    
  2.    
  3. public class ArrayList<E> extends AbstractList<E>    
  4.         implements List<E>, RandomAccess, Cloneable, java.io.Serializable    
  5. {    
  6.     // 序列版本号号    
  7.     private static final long serialVersionUID = 8683452581122892189L;    
  8.    
  9.     // ArrayList基于该数组实现,用该数组保存数据   
  10.     private transient Object[] elementData;    
  11.    
  12.     // ArrayList中实际数据的数量    
  13.     private int size;    
  14.    
  15.     // ArrayList带容量大小的构造函数。    
  16.     public ArrayList(int initialCapacity) {    
  17.         super();    
  18.         if (initialCapacity < 0)    
  19.             throw new IllegalArgumentException("Illegal Capacity: "+    
  20.                                                initialCapacity);    
  21.         // 新建一个数组    
  22.         this.elementData = new Object[initialCapacity];    
  23.     }    
  24.    
  25.     // ArrayList无參构造函数。默认容量是10。    
  26.     public ArrayList() {    
  27.         this(10);    
  28.     }    
  29.    
  30.     // 创建一个包括collection的ArrayList    
  31.     public ArrayList(Collection<? extends E> c) {    
  32.         elementData = c.toArray();    
  33.         size = elementData.length;    
  34.         if (elementData.getClass() != Object[].class)    
  35.             elementData = Arrays.copyOf(elementData, size, Object[].class);    
  36.     }    
  37.    
  38.    
  39.     // 将当前容量值设为实际元素个数    
  40.     public void trimToSize() {    
  41.         modCount++;    
  42.         int oldCapacity = elementData.length;    
  43.         if (size < oldCapacity) {    
  44.             elementData = Arrays.copyOf(elementData, size);    
  45.         }    
  46.     }    
  47.    
  48.    
  49.     // 确定ArrarList的容量。

        

  50.     // 若ArrayList的容量不足以容纳当前的所有元素,设置 新的容量=“(原始容量x3)/2 + 1”    
  51.     public void ensureCapacity(int minCapacity) {    
  52.         // 将“改动统计数”+1。该变量主要是用来实现fail-fast机制的    
  53.         modCount++;    
  54.         int oldCapacity = elementData.length;    
  55.         // 若当前容量不足以容纳当前的元素个数。设置 新的容量=“(原始容量x3)/2 + 1”    
  56.         if (minCapacity > oldCapacity) {    
  57.             Object oldData[] = elementData;    
  58.             int newCapacity = (oldCapacity * 3)/2 + 1;    
  59.             //假设还不够,则直接将minCapacity设置为当前容量  
  60.             if (newCapacity < minCapacity)    
  61.                 newCapacity = minCapacity;    
  62.             elementData = Arrays.copyOf(elementData, newCapacity);    
  63.         }    
  64.     }    
  65.    
  66.     // 加入元素e    
  67.     public boolean add(E e) {    
  68.         // 确定ArrayList的容量大小    
  69.         ensureCapacity(size + 1);  // Increments modCount!!    
  70.         // 加入e到ArrayList中    
  71.         elementData[size++] = e;    
  72.         return true;    
  73.     }    
  74.    
  75.     // 返回ArrayList的实际大小    
  76.     public int size() {    
  77.         return size;    
  78.     }    
  79.    
  80.     // ArrayList是否包括Object(o)    
  81.     public boolean contains(Object o) {    
  82.         return indexOf(o) >= 0;    
  83.     }    
  84.    
  85.     //返回ArrayList是否为空    
  86.     public boolean isEmpty() {    
  87.         return size == 0;    
  88.     }    
  89.    
  90.     // 正向查找。返回元素的索引值    
  91.     public int indexOf(Object o) {    
  92.         if (o == null) {    
  93.             for (int i = 0; i < size; i++)    
  94.             if (elementData[i]==null)    
  95.                 return i;    
  96.             } else {    
  97.                 for (int i = 0; i < size; i++)    
  98.                 if (o.equals(elementData[i]))    
  99.                     return i;    
  100.             }    
  101.             return -1;    
  102.         }    
  103.    
  104.         // 反向查找。返回元素的索引值    
  105.         public int lastIndexOf(Object o) {    
  106.         if (o == null) {    
  107.             for (int i = size-1; i >= 0; i--)    
  108.             if (elementData[i]==null)    
  109.                 return i;    
  110.         } else {    
  111.             for (int i = size-1; i >= 0; i--)    
  112.             if (o.equals(elementData[i]))    
  113.                 return i;    
  114.         }    
  115.         return -1;    
  116.     }    
  117.    
  118.     // 反向查找(从数组末尾向開始查找)。返回元素(o)的索引值    
  119.     public int lastIndexOf(Object o) {    
  120.         if (o == null) {    
  121.             for (int i = size-1; i >= 0; i--)    
  122.             if (elementData[i]==null)    
  123.                 return i;    
  124.         } else {    
  125.             for (int i = size-1; i >= 0; i--)    
  126.             if (o.equals(elementData[i]))    
  127.                 return i;    
  128.         }    
  129.         return -1;    
  130.     }    
  131.      
  132.    
  133.     // 返回ArrayList的Object数组    
  134.     public Object[] toArray() {    
  135.         return Arrays.copyOf(elementData, size);    
  136.     }    
  137.    
  138.     // 返回ArrayList元素组成的数组  
  139.     public <T> T[] toArray(T[] a) {    
  140.         // 若数组a的大小 < ArrayList的元素个数;    
  141.         // 则新建一个T[]数组。数组大小是“ArrayList的元素个数”,并将“ArrayList”所有复制到新数组中    
  142.         if (a.length < size)    
  143.             return (T[]) Arrays.copyOf(elementData, size, a.getClass());    
  144.    
  145.         // 若数组a的大小 >= ArrayList的元素个数;    
  146.         // 则将ArrayList的所有元素都复制到数组a中。

        

  147.         System.arraycopy(elementData, 0, a, 0, size);    
  148.         if (a.length > size)    
  149.             a[size] = null;    
  150.         return a;    
  151.     }    
  152.    
  153.     // 获取index位置的元素值    
  154.     public E get(int index) {    
  155.         RangeCheck(index);    
  156.    
  157.         return (E) elementData[index];    
  158.     }    
  159.    
  160.     // 设置index位置的值为element    
  161.     public E set(int index, E element) {    
  162.         RangeCheck(index);    
  163.    
  164.         E oldValue = (E) elementData[index];    
  165.         elementData[index] = element;    
  166.         return oldValue;    
  167.     }    
  168.    
  169.     // 将e加入到ArrayList中    
  170.     public boolean add(E e) {    
  171.         ensureCapacity(size + 1);  // Increments modCount!!    
  172.         elementData[size++] = e;    
  173.         return true;    
  174.     }    
  175.    
  176.     // 将e加入到ArrayList的指定位置    
  177.     public void add(int index, E element) {    
  178.         if (index > size || index < 0)    
  179.             throw new IndexOutOfBoundsException(    
  180.             "Index: "+index+", Size: "+size);    
  181.    
  182.         ensureCapacity(size+1);  // Increments modCount!!    
  183.         System.arraycopy(elementData, index, elementData, index + 1,    
  184.              size - index);    
  185.         elementData[index] = element;    
  186.         size++;    
  187.     }    
  188.    
  189.     // 删除ArrayList指定位置的元素    
  190.     public E remove(int index) {    
  191.         RangeCheck(index);    
  192.    
  193.         modCount++;    
  194.         E oldValue = (E) elementData[index];    
  195.    
  196.         int numMoved = size - index - 1;    
  197.         if (numMoved > 0)    
  198.             System.arraycopy(elementData, index+1, elementData, index,    
  199.                  numMoved);    
  200.         elementData[--size] = null// Let gc do its work    
  201.    
  202.         return oldValue;    
  203.     }    
  204.    
  205.     // 删除ArrayList的指定元素    
  206.     public boolean remove(Object o) {    
  207.         if (o == null) {    
  208.                 for (int index = 0; index < size; index++)    
  209.             if (elementData[index] == null) {    
  210.                 fastRemove(index);    
  211.                 return true;    
  212.             }    
  213.         } else {    
  214.             for (int index = 0; index < size; index++)    
  215.             if (o.equals(elementData[index])) {    
  216.                 fastRemove(index);    
  217.                 return true;    
  218.             }    
  219.         }    
  220.         return false;    
  221.     }    
  222.    
  223.    
  224.     // 高速删除第index个元素    
  225.     private void fastRemove(int index) {    
  226.         modCount++;    
  227.         int numMoved = size - index - 1;    
  228.         // 从"index+1"開始。用后面的元素替换前面的元素。

        

  229.         if (numMoved > 0)    
  230.             System.arraycopy(elementData, index+1, elementData, index,    
  231.                              numMoved);    
  232.         // 将最后一个元素设为null    
  233.         elementData[--size] = null// Let gc do its work    
  234.     }    
  235.    
  236.     // 删除元素    
  237.     public boolean remove(Object o) {    
  238.         if (o == null) {    
  239.             for (int index = 0; index < size; index++)    
  240.             if (elementData[index] == null) {    
  241.                 fastRemove(index);    
  242.             return true;    
  243.             }    
  244.         } else {    
  245.             // 便利ArrayList,找到“元素o”。则删除,并返回true。    
  246.             for (int index = 0; index < size; index++)    
  247.             if (o.equals(elementData[index])) {    
  248.                 fastRemove(index);    
  249.             return true;    
  250.             }    
  251.         }    
  252.         return false;    
  253.     }    
  254.    
  255.     // 清空ArrayList,将所有的元素设为null    
  256.     public void clear() {    
  257.         modCount++;    
  258.    
  259.         for (int i = 0; i < size; i++)    
  260.             elementData[i] = null;    
  261.    
  262.         size = 0;    
  263.     }    
  264.    
  265.     // 将集合c追加到ArrayList中    
  266.     public boolean addAll(Collection<?

     extends E> c) {    

  267.         Object[] a = c.toArray();    
  268.         int numNew = a.length;    
  269.         ensureCapacity(size + numNew);  // Increments modCount    
  270.         System.arraycopy(a, 0, elementData, size, numNew);    
  271.         size += numNew;    
  272.         return numNew != 0;    
  273.     }    
  274.    
  275.     // 从index位置開始,将集合c加入到ArrayList    
  276.     public boolean addAll(int index, Collection<?

     extends E> c) {    

  277.         if (index > size || index < 0)    
  278.             throw new IndexOutOfBoundsException(    
  279.             "Index: " + index + ", Size: " + size);    
  280.    
  281.         Object[] a = c.toArray();    
  282.         int numNew = a.length;    
  283.         ensureCapacity(size + numNew);  // Increments modCount    
  284.    
  285.         int numMoved = size - index;    
  286.         if (numMoved > 0)    
  287.             System.arraycopy(elementData, index, elementData, index + numNew,    
  288.                  numMoved);    
  289.    
  290.         System.arraycopy(a, 0, elementData, index, numNew);    
  291.         size += numNew;    
  292.         return numNew != 0;    
  293.     }    
  294.    
  295.     // 删除fromIndex到toIndex之间的所有元素。    
  296.     protected void removeRange(int fromIndex, int toIndex) {    
  297.     modCount++;    
  298.     int numMoved = size - toIndex;    
  299.         System.arraycopy(elementData, toIndex, elementData, fromIndex,    
  300.                          numMoved);    
  301.    
  302.     // Let gc do its work    
  303.     int newSize = size - (toIndex-fromIndex);    
  304.     while (size != newSize)    
  305.         elementData[--size] = null;    
  306.     }    
  307.    
  308.     private void RangeCheck(int index) {    
  309.     if (index >= size)    
  310.         throw new IndexOutOfBoundsException(    
  311.         "Index: "+index+", Size: "+size);    
  312.     }    
  313.    
  314.    
  315.     // 克隆函数    
  316.     public Object clone() {    
  317.         try {    
  318.             ArrayList<E> v = (ArrayList<E>) super.clone();    
  319.             // 将当前ArrayList的所有元素复制到v中    
  320.             v.elementData = Arrays.copyOf(elementData, size);    
  321.             v.modCount = 0;    
  322.             return v;    
  323.         } catch (CloneNotSupportedException e) {    
  324.             // this shouldn't happen, since we are Cloneable    
  325.             throw new InternalError();    
  326.         }    
  327.     }    
  328.    
  329.    
  330.     // java.io.Serializable的写入函数    
  331.     // 将ArrayList的“容量,所有的元素值”都写入到输出流中    
  332.     private void writeObject(java.io.ObjectOutputStream s)    
  333.         throws java.io.IOException{    
  334.     // Write out element count, and any hidden stuff    
  335.     int expectedModCount = modCount;    
  336.     s.defaultWriteObject();    
  337.    
  338.         // 写入“数组的容量”    
  339.         s.writeInt(elementData.length);    
  340.    
  341.     // 写入“数组的每一个元素”    
  342.     for (int i=0; i<size; i++)    
  343.             s.writeObject(elementData[i]);    
  344.    
  345.     if (modCount != expectedModCount) {    
  346.             throw new ConcurrentModificationException();    
  347.         }    
  348.    
  349.     }    
  350.    
  351.    
  352.     // java.io.Serializable的读取函数:依据写入方式读出    
  353.     // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出    
  354.     private void readObject(java.io.ObjectInputStream s)    
  355.         throws java.io.IOException, ClassNotFoundException {    
  356.         // Read in size, and any hidden stuff    
  357.         s.defaultReadObject();    
  358.    
  359.         // 从输入流中读取ArrayList的“容量”    
  360.         int arrayLength = s.readInt();    
  361.         Object[] a = elementData = new Object[arrayLength];    
  362.    
  363.         // 从输入流中将“所有的元素值”读出    
  364.         for (int i=0; i<size; i++)    
  365.             a[i] = s.readObject();    
  366.     }    
  367. }  


几点总结

关于ArrayList的源代码。给出几点比較重要的总结:

    1、注意其三个不同的构造方法。

无參构造方法构造的ArrayList的容量默觉得10。带有Collection參数的构造方法,将Collection转化为数组赋给ArrayList的实现数组elementData。

    2、注意扩充容量的方法ensureCapacity。ArrayList在每次添加元素(可能是1个,也可能是一组)时。都要调用该方法来确保足够的容量。

当容量不足以容纳当前的元素个数时,就设置新的容量为旧的容量的1.5倍加1,假设设置后的新容量还不够,则直接新容量设置为传入的參数(也就是所需的容量)。而后用Arrays.copyof()方法将元素复制到新的数组(详见以下的第3点)。

从中能够看出。当容量不够时,每次添加元素,都要将原来的元素复制到一个新的数组中。非常之耗时,也因此建议在事先能确定元素数量的情况下,才使用ArrayList,否则建议使用LinkedList。

    3、ArrayList的实现中大量地调用了Arrays.copyof()和System.arraycopy()方法。我们有必要对这两个方法的实现做下深入的了解。

    首先来看Arrays.copyof()方法。它有非常多个重载的方法。但实现思路都是一样的。我们来看泛型版本号的源代码:

  1. public static <T> T[] copyOf(T[] original, int newLength) {  
  2.     return (T[]) copyOf(original, newLength, original.getClass());  
  3. }  

    非常明显调用了还有一个copyof方法,该方法有三个參数,最后一个參数指明要转换的数据的类型,其源代码例如以下:

  1. public static <T,U> T[] copyOf(U[] original, int newLength, Class<?

     extends T[]> newType) {  

  2.     T[] copy = ((Object)newType == (Object)Object[].class)  
  3.         ? (T[]) new Object[newLength]  
  4.         : (T[]) Array.newInstance(newType.getComponentType(), newLength);  
  5.     System.arraycopy(original, 0, copy, 0,  
  6.                      Math.min(original.length, newLength));  
  7.     return copy;  
  8. }  

    这里能够非常明显地看出,该方法实际上是在其内部又创建了一个长度为newlength的数组,调用System.arraycopy()方法,将原来数组中的元素复制到了新的数组中。

    以下来看System.arraycopy()方法。

该方法被标记了native,调用了系统的C/C++代码,在JDK中是看不到的,但在openJDK中能够看到其源代码。该函数实际上终于调用了C语言的memmove()函数。因此它能够保证同一个数组内元素的正确复制和移动,比一般的复制方法的实现效率要高非常多,非常适合用来批量处理数组。

Java强烈推荐在复制大量数组元素时用该方法,以取得更高的效率。

    4、注意ArrayList的两个转化为静态数组的toArray方法。

    第一个。Object[] toArray()方法。该方法有可能会抛出java.lang.ClassCastException异常。假设直接用向下转型的方法,将整个ArrayList集合转变为指定类型的Array数组。便会抛出该异常。而假设转化为Array数组时不向下转型,而是将每一个元素向下转型,则不会抛出该异常,显然对数组中的元素一个个进行向下转型,效率不高。且不太方便。

    第二个,<T> T[] toArray(T[] a)方法。

该方法能够直接将ArrayList转换得到的Array进行总体向下转型(转型事实上是在该方法的源代码中实现的)。且从该方法的源代码中能够看出,參数a的大小不足时,内部会调用Arrays.copyOf方法,该方法内部创建一个新的数组返回,因此对该方法的经常使用形式例如以下:

  1. public static Integer[] vectorToArray2(ArrayList<Integer> v) {    
  2.     Integer[] newText = (Integer[])v.toArray(new Integer[0]);    
  3.     return newText;    
  4. }    

     5、ArrayList基于数组实现,能够通过下标索引直接查找到指定位置的元素。因此查找效率高,但每次插入或删除元素。就要大量地移动元素,插入删除元素的效率低。

    6、在查找给定元素索引值等的方法中,源代码都将该元素的值分为null和不为null两种情况处理。ArrayList中同意元素为null。


LinkedList源代码剖析

LinkedList简单介绍

    LinkedList是基于双向循环链表(从源代码中能够非常easy看出)实现的,除了能够当做链表来操作外,它还能够当做栈、队列和双端队列来使用。

    LinkedList相同是非线程安全的,仅仅在单线程下适合使用。

    LinkedList实现了Serializable接口,因此它支持序列化。能够通过序列化传输,实现了Cloneable接口,能被克隆。


LinkedList源代码剖析

    LinkedList的源代码例如以下(加入了比較具体的凝视):

  1. package java.util;    
  2.    
  3. public class LinkedList<E>    
  4.     extends AbstractSequentialList<E>    
  5.     implements List<E>, Deque<E>, Cloneable, java.io.Serializable    
  6. {    
  7.     // 链表的表头,表头不包括不论什么数据。Entry是个链表类数据结构。

        

  8.     private transient Entry<E> header = new Entry<E>(nullnullnull);    
  9.    
  10.     // LinkedList中元素个数    
  11.     private transient int size = 0;    
  12.    
  13.     // 默认构造函数:创建一个空的链表    
  14.     public LinkedList() {    
  15.         header.next = header.previous = header;    
  16.     }    
  17.    
  18.     // 包括“集合”的构造函数:创建一个包括“集合”的LinkedList    
  19.     public LinkedList(Collection<? extends E> c) {    
  20.         this();    
  21.         addAll(c);    
  22.     }    
  23.    
  24.     // 获取LinkedList的第一个元素    
  25.     public E getFirst() {    
  26.         if (size==0)    
  27.             throw new NoSuchElementException();    
  28.    
  29.         // 链表的表头header中不包括数据。    
  30.         // 这里返回header所指下一个节点所包括的数据。

        

  31.         return header.next.element;    
  32.     }    
  33.    
  34.     // 获取LinkedList的最后一个元素    
  35.     public E getLast()  {    
  36.         if (size==0)    
  37.             throw new NoSuchElementException();    
  38.    
  39.         // 因为LinkedList是双向链表;而表头header不包括数据。    
  40.         // 因而。这里返回表头header的前一个节点所包括的数据。

        

  41.         return header.previous.element;    
  42.     }    
  43.    
  44.     // 删除LinkedList的第一个元素    
  45.     public E removeFirst() {    
  46.         return remove(header.next);    
  47.     }    
  48.    
  49.     // 删除LinkedList的最后一个元素    
  50.     public E removeLast() {    
  51.         return remove(header.previous);    
  52.     }    
  53.    
  54.     // 将元素加入到LinkedList的起始位置    
  55.     public void addFirst(E e) {    
  56.         addBefore(e, header.next);    
  57.     }    
  58.    
  59.     // 将元素加入到LinkedList的结束位置    
  60.     public void addLast(E e) {    
  61.         addBefore(e, header);    
  62.     }    
  63.    
  64.     // 推断LinkedList是否包括元素(o)    
  65.     public boolean contains(Object o) {    
  66.         return indexOf(o) != -1;    
  67.     }    
  68.    
  69.     // 返回LinkedList的大小    
  70.     public int size() {    
  71.         return size;    
  72.     }    
  73.    
  74.     // 将元素(E)加入到LinkedList中    
  75.     public boolean add(E e) {    
  76.         // 将节点(节点数据是e)加入到表头(header)之前。

        

  77.         // 即,将节点加入到双向链表的末端。    
  78.         addBefore(e, header);    
  79.         return true;    
  80.     }    
  81.    
  82.     // 从LinkedList中删除元素(o)    
  83.     // 从链表開始查找。如存在元素(o)则删除该元素并返回true;    
  84.     // 否则,返回false。    
  85.     public boolean remove(Object o) {    
  86.         if (o==null) {    
  87.             // 若o为null的删除情况    
  88.             for (Entry<E> e = header.next; e != header; e = e.next) {    
  89.                 if (e.element==null) {    
  90.                     remove(e);    
  91.                     return true;    
  92.                 }    
  93.             }    
  94.         } else {    
  95.             // 若o不为null的删除情况    
  96.             for (Entry<E> e = header.next; e != header; e = e.next) {    
  97.                 if (o.equals(e.element)) {    
  98.                     remove(e);    
  99.                     return true;    
  100.                 }    
  101.             }    
  102.         }    
  103.         return false;    
  104.     }    
  105.    
  106.     // 将“集合(c)”加入到LinkedList中。    
  107.     // 实际上,是从双向链表的末尾開始,将“集合(c)”加入到双向链表中。    
  108.     public boolean addAll(Collection<?

     extends E> c) {    

  109.         return addAll(size, c);    
  110.     }    
  111.    
  112.     // 从双向链表的index開始。将“集合(c)”加入到双向链表中。

        

  113.     public boolean addAll(int index, Collection<? extends E> c) {    
  114.         if (index < 0 || index > size)    
  115.             throw new IndexOutOfBoundsException("Index: "+index+    
  116.                                                 ", Size: "+size);    
  117.         Object[] a = c.toArray();    
  118.         // 获取集合的长度    
  119.         int numNew = a.length;    
  120.         if (numNew==0)    
  121.             return false;    
  122.         modCount++;    
  123.    
  124.         // 设置“当前要插入节点的后一个节点”    
  125.         Entry<E> successor = (index==size ? header : entry(index));    
  126.         // 设置“当前要插入节点的前一个节点”    
  127.         Entry<E> predecessor = successor.previous;    
  128.         // 将集合(c)所有插入双向链表中    
  129.         for (int i=0; i<numNew; i++) {    
  130.             Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);    
  131.             predecessor.next = e;    
  132.             predecessor = e;    
  133.         }    
  134.         successor.previous = predecessor;    
  135.    
  136.         // 调整LinkedList的实际大小    
  137.         size += numNew;    
  138.         return true;    
  139.     }    
  140.    
  141.     // 清空双向链表    
  142.     public void clear() {    
  143.         Entry<E> e = header.next;    
  144.         // 从表头開始,逐个向后遍历。对遍历到的节点运行一下操作:    
  145.         // (01) 设置前一个节点为null     
  146.         // (02) 设置当前节点的内容为null     
  147.         // (03) 设置后一个节点为“新的当前节点”    
  148.         while (e != header) {    
  149.             Entry<E> next = e.next;    
  150.             e.next = e.previous = null;    
  151.             e.element = null;    
  152.             e = next;    
  153.         }    
  154.         header.next = header.previous = header;    
  155.         // 设置大小为0    
  156.         size = 0;    
  157.         modCount++;    
  158.     }    
  159.    
  160.     // 返回LinkedList指定位置的元素    
  161.     public E get(int index) {    
  162.         return entry(index).element;    
  163.     }    
  164.    
  165.     // 设置index位置相应的节点的值为element    
  166.     public E set(int index, E element) {    
  167.         Entry<E> e = entry(index);    
  168.         E oldVal = e.element;    
  169.         e.element = element;    
  170.         return oldVal;    
  171.     }    
  172.      
  173.     // 在index前加入节点,且节点的值为element    
  174.     public void add(int index, E element) {    
  175.         addBefore(element, (index==size ?

     header : entry(index)));    

  176.     }    
  177.    
  178.     // 删除index位置的节点    
  179.     public E remove(int index) {    
  180.         return remove(entry(index));    
  181.     }    
  182.    
  183.     // 获取双向链表中指定位置的节点    
  184.     private Entry<E> entry(int index) {    
  185.         if (index < 0 || index >= size)    
  186.             throw new IndexOutOfBoundsException("Index: "+index+    
  187.                                                 ", Size: "+size);    
  188.         Entry<E> e = header;    
  189.         // 获取index处的节点。    
  190.         // 若index < 双向链表长度的1/2,则从前先后查找;    
  191.         // 否则,从后向前查找。    
  192.         if (index < (size >> 1)) {    
  193.             for (int i = 0; i <= index; i++)    
  194.                 e = e.next;    
  195.         } else {    
  196.             for (int i = size; i > index; i--)    
  197.                 e = e.previous;    
  198.         }    
  199.         return e;    
  200.     }    
  201.    
  202.     // 从前向后查找。返回“值为对象(o)的节点相应的索引”    
  203.     // 不存在就返回-1    
  204.     public int indexOf(Object o) {    
  205.         int index = 0;    
  206.         if (o==null) {    
  207.             for (Entry e = header.next; e != header; e = e.next) {    
  208.                 if (e.element==null)    
  209.                     return index;    
  210.                 index++;    
  211.             }    
  212.         } else {    
  213.             for (Entry e = header.next; e != header; e = e.next) {    
  214.                 if (o.equals(e.element))    
  215.                     return index;    
  216.                 index++;    
  217.             }    
  218.         }    
  219.         return -1;    
  220.     }    
  221.    
  222.     // 从后向前查找,返回“值为对象(o)的节点相应的索引”    
  223.     // 不存在就返回-1    
  224.     public int lastIndexOf(Object o) {    
  225.         int index = size;    
  226.         if (o==null) {    
  227.             for (Entry e = header.previous; e != header; e = e.previous) {    
  228.                 index--;    
  229.                 if (e.element==null)    
  230.                     return index;    
  231.             }    
  232.         } else {    
  233.             for (Entry e = header.previous; e != header; e = e.previous) {    
  234.                 index--;    
  235.                 if (o.equals(e.element))    
  236.                     return index;    
  237.             }    
  238.         }    
  239.         return -1;    
  240.     }    
  241.    
  242.     // 返回第一个节点    
  243.     // 若LinkedList的大小为0,则返回null    
  244.     public E peek() {    
  245.         if (size==0)    
  246.             return null;    
  247.         return getFirst();    
  248.     }    
  249.    
  250.     // 返回第一个节点    
  251.     // 若LinkedList的大小为0,则抛出异常    
  252.     public E element() {    
  253.         return getFirst();    
  254.     }    
  255.    
  256.     // 删除并返回第一个节点    
  257.     // 若LinkedList的大小为0,则返回null    
  258.     public E poll() {    
  259.         if (size==0)    
  260.             return null;    
  261.         return removeFirst();    
  262.     }    
  263.    
  264.     // 将e加入双向链表末尾    
  265.     public boolean offer(E e) {    
  266.         return add(e);    
  267.     }    
  268.    
  269.     // 将e加入双向链表开头    
  270.     public boolean offerFirst(E e) {    
  271.         addFirst(e);    
  272.         return true;    
  273.     }    
  274.    
  275.     // 将e加入双向链表末尾    
  276.     public boolean offerLast(E e) {    
  277.         addLast(e);    
  278.         return true;    
  279.     }    
  280.    
  281.     // 返回第一个节点    
  282.     // 若LinkedList的大小为0,则返回null    
  283.     public E peekFirst() {    
  284.         if (size==0)    
  285.             return null;    
  286.         return getFirst();    
  287.     }    
  288.    
  289.     // 返回最后一个节点    
  290.     // 若LinkedList的大小为0,则返回null    
  291.     public E peekLast() {    
  292.         if (size==0)    
  293.             return null;    
  294.         return getLast();    
  295.     }    
  296.    
  297.     // 删除并返回第一个节点    
  298.     // 若LinkedList的大小为0,则返回null    
  299.     public E pollFirst() {    
  300.         if (size==0)    
  301.             return null;    
  302.         return removeFirst();    
  303.     }    
  304.    
  305.     // 删除并返回最后一个节点    
  306.     // 若LinkedList的大小为0,则返回null    
  307.     public E pollLast() {    
  308.         if (size==0)    
  309.             return null;    
  310.         return removeLast();    
  311.     }    
  312.    
  313.     // 将e插入到双向链表开头    
  314.     public void push(E e) {    
  315.         addFirst(e);    
  316.     }    
  317.    
  318.     // 删除并返回第一个节点    
  319.     public E pop() {    
  320.         return removeFirst();    
  321.     }    
  322.    
  323.     // 从LinkedList開始向后查找。删除第一个值为元素(o)的节点    
  324.     // 从链表開始查找。如存在节点的值为元素(o)的节点,则删除该节点    
  325.     public boolean removeFirstOccurrence(Object o) {    
  326.         return remove(o);    
  327.     }    
  328.    
  329.     // 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点    
  330.     // 从链表開始查找,如存在节点的值为元素(o)的节点。则删除该节点    
  331.     public boolean removeLastOccurrence(Object o) {    
  332.         if (o==null) {    
  333.             for (Entry<E> e = header.previous; e != header; e = e.previous) {    
  334.                 if (e.element==null) {    
  335.                     remove(e);    
  336.                     return true;    
  337.                 }    
  338.             }    
  339.         } else {    
  340.             for (Entry<E> e = header.previous; e != header; e = e.previous) {    
  341.                 if (o.equals(e.element)) {    
  342.                     remove(e);    
  343.                     return true;    
  344.                 }    
  345.             }    
  346.         }    
  347.         return false;    
  348.     }    
  349.    
  350.     // 返回“index到末尾的所有节点”相应的ListIterator对象(List迭代器)    
  351.     public ListIterator<E> listIterator(int index) {    
  352.         return new ListItr(index);    
  353.     }    
  354.    
  355.     // List迭代器    
  356.     private class ListItr implements ListIterator<E> {    
  357.         // 上一次返回的节点    
  358.         private Entry<E> lastReturned = header;    
  359.         // 下一个节点    
  360.         private Entry<E> next;    
  361.         // 下一个节点相应的索引值    
  362.         private int nextIndex;    
  363.         // 期望的改变计数。

    用来实现fail-fast机制。

        

  364.         private int expectedModCount = modCount;    
  365.    
  366.         // 构造函数。

        

  367.         // 从index位置開始进行迭代    
  368.         ListItr(int index) {    
  369.             // index的有效性处理    
  370.             if (index < 0 || index > size)    
  371.                 throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);    
  372.             // 若 “index 小于 ‘双向链表长度的一半’”,则从第一个元素開始往后查找;    
  373.             // 否则,从最后一个元素往前查找。    
  374.             if (index < (size >> 1)) {    
  375.                 next = header.next;    
  376.                 for (nextIndex=0; nextIndex<index; nextIndex++)    
  377.                     next = next.next;    
  378.             } else {    
  379.                 next = header;    
  380.                 for (nextIndex=size; nextIndex>index; nextIndex--)    
  381.                     next = next.previous;    
  382.             }    
  383.         }    
  384.    
  385.         // 是否存在下一个元素    
  386.         public boolean hasNext() {    
  387.             // 通过元素索引是否等于“双向链表大小”来推断是否达到最后。    
  388.             return nextIndex != size;    
  389.         }    
  390.    
  391.         // 获取下一个元素    
  392.         public E next() {    
  393.             checkForComodification();    
  394.             if (nextIndex == size)    
  395.                 throw new NoSuchElementException();    
  396.    
  397.             lastReturned = next;    
  398.             // next指向链表的下一个元素    
  399.             next = next.next;    
  400.             nextIndex++;    
  401.             return lastReturned.element;    
  402.         }    
  403.    
  404.         // 是否存在上一个元素    
  405.         public boolean hasPrevious() {    
  406.             // 通过元素索引是否等于0。来推断是否达到开头。

        

  407.             return nextIndex != 0;    
  408.         }    
  409.    
  410.         // 获取上一个元素    
  411.         public E previous() {    
  412.             if (nextIndex == 0)    
  413.             throw new NoSuchElementException();    
  414.    
  415.             // next指向链表的上一个元素    
  416.             lastReturned = next = next.previous;    
  417.             nextIndex--;    
  418.             checkForComodification();    
  419.             return lastReturned.element;    
  420.         }    
  421.    
  422.         // 获取下一个元素的索引    
  423.         public int nextIndex() {    
  424.             return nextIndex;    
  425.         }    
  426.    
  427.         // 获取上一个元素的索引    
  428.         public int previousIndex() {    
  429.             return nextIndex-1;    
  430.         }    
  431.    
  432.         // 删除当前元素。    
  433.         // 删除双向链表中的当前节点    
  434.         public void remove() {    
  435.             checkForComodification();    
  436.             Entry<E> lastNext = lastReturned.next;    
  437.             try {    
  438.                 LinkedList.this.remove(lastReturned);    
  439.             } catch (NoSuchElementException e) {    
  440.                 throw new IllegalStateException();    
  441.             }    
  442.             if (next==lastReturned)    
  443.                 next = lastNext;    
  444.             else   
  445.                 nextIndex--;    
  446.             lastReturned = header;    
  447.             expectedModCount++;    
  448.         }    
  449.    
  450.         // 设置当前节点为e    
  451.         public void set(E e) {    
  452.             if (lastReturned == header)    
  453.                 throw new IllegalStateException();    
  454.             checkForComodification();    
  455.             lastReturned.element = e;    
  456.         }    
  457.    
  458.         // 将e加入到当前节点的前面    
  459.         public void add(E e) {    
  460.             checkForComodification();    
  461.             lastReturned = header;    
  462.             addBefore(e, next);    
  463.             nextIndex++;    
  464.             expectedModCount++;    
  465.         }    
  466.    
  467.         // 推断 “modCount和expectedModCount是否相等”,依次来实现fail-fast机制。

        

  468.         final void checkForComodification() {    
  469.             if (modCount != expectedModCount)    
  470.             throw new ConcurrentModificationException();    
  471.         }    
  472.     }    
  473.    
  474.     // 双向链表的节点所相应的数据结构。

        

  475.     // 包括3部分:上一节点,下一节点。当前节点值。    
  476.     private static class Entry<E> {    
  477.         // 当前节点所包括的值    
  478.         E element;    
  479.         // 下一个节点    
  480.         Entry<E> next;    
  481.         // 上一个节点    
  482.         Entry<E> previous;    
  483.    
  484.         /**   
  485.          * 链表节点的构造函数。

       

  486.          * 參数说明:   
  487.          *   element  —— 节点所包括的数据   
  488.          *   next      —— 下一个节点   
  489.          *   previous —— 上一个节点   
  490.          */   
  491.         Entry(E element, Entry<E> next, Entry<E> previous) {    
  492.             this.element = element;    
  493.             this.next = next;    
  494.             this.previous = previous;    
  495.         }    
  496.     }    
  497.    
  498.     // 将节点(节点数据是e)加入到entry节点之前。

        

  499.     private Entry<E> addBefore(E e, Entry<E> entry) {    
  500.         // 新建节点newEntry。将newEntry插入到节点e之前;而且设置newEntry的数据是e    
  501.         Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);    
  502.         newEntry.previous.next = newEntry;    
  503.         newEntry.next.previous = newEntry;    
  504.         // 改动LinkedList大小    
  505.         size++;    
  506.         // 改动LinkedList的改动统计数:用来实现fail-fast机制。

        

  507.         modCount++;    
  508.         return newEntry;    
  509.     }    
  510.    
  511.     // 将节点从链表中删除    
  512.     private E remove(Entry<E> e) {    
  513.         if (e == header)    
  514.             throw new NoSuchElementException();    
  515.    
  516.         E result = e.element;    
  517.         e.previous.next = e.next;    
  518.         e.next.previous = e.previous;    
  519.         e.next = e.previous = null;    
  520.         e.element = null;    
  521.         size--;    
  522.         modCount++;    
  523.         return result;    
  524.     }    
  525.    
  526.     // 反向迭代器    
  527.     public Iterator<E> descendingIterator() {    
  528.         return new DescendingIterator();    
  529.     }    
  530.    
  531.     // 反向迭代器实现类。    
  532.     private class DescendingIterator implements Iterator {    
  533.         final ListItr itr = new ListItr(size());    
  534.         // 反向迭代器是否下一个元素。    
  535.         // 实际上是推断双向链表的当前节点是否达到开头    
  536.         public boolean hasNext() {    
  537.             return itr.hasPrevious();    
  538.         }    
  539.         // 反向迭代器获取下一个元素。

        

  540.         // 实际上是获取双向链表的前一个节点    
  541.         public E next() {    
  542.             return itr.previous();    
  543.         }    
  544.         // 删除当前节点    
  545.         public void remove() {    
  546.             itr.remove();    
  547.         }    
  548.     }    
  549.    
  550.    
  551.     // 返回LinkedList的Object[]数组    
  552.     public Object[] toArray() {    
  553.     // 新建Object[]数组    
  554.     Object[] result = new Object[size];    
  555.         int i = 0;    
  556.         // 将链表中所有节点的数据都加入到Object[]数组中    
  557.         for (Entry<E> e = header.next; e != header; e = e.next)    
  558.             result[i++] = e.element;    
  559.     return result;    
  560.     }    
  561.    
  562.     // 返回LinkedList的模板数组。所谓模板数组,即能够将T设为随意的数据类型    
  563.     public <T> T[] toArray(T[] a) {    
  564.         // 若数组a的大小 < LinkedList的元素个数(意味着数组a不能容纳LinkedList中所有元素)    
  565.         // 则新建一个T[]数组,T[]的大小为LinkedList大小,并将该T[]赋值给a。    
  566.         if (a.length < size)    
  567.             a = (T[])java.lang.reflect.Array.newInstance(    
  568.                                 a.getClass().getComponentType(), size);    
  569.         // 将链表中所有节点的数据都加入到数组a中    
  570.         int i = 0;    
  571.         Object[] result = a;    
  572.         for (Entry<E> e = header.next; e != header; e = e.next)    
  573.             result[i++] = e.element;    
  574.    
  575.         if (a.length > size)    
  576.             a[size] = null;    
  577.    
  578.         return a;    
  579.     }    
  580.    
  581.    
  582.     // 克隆函数。返回LinkedList的克隆对象。    
  583.     public Object clone() {    
  584.         LinkedList<E> clone = null;    
  585.         // 克隆一个LinkedList克隆对象    
  586.         try {    
  587.             clone = (LinkedList<E>) super.clone();    
  588.         } catch (CloneNotSupportedException e) {    
  589.             throw new InternalError();    
  590.         }    
  591.    
  592.         // 新建LinkedList表头节点    
  593.         clone.header = new Entry<E>(nullnullnull);    
  594.         clone.header.next = clone.header.previous = clone.header;    
  595.         clone.size = 0;    
  596.         clone.modCount = 0;    
  597.    
  598.         // 将链表中所有节点的数据都加入到克隆对象中    
  599.         for (Entry<E> e = header.next; e != header; e = e.next)    
  600.             clone.add(e.element);    
  601.    
  602.         return clone;    
  603.     }    
  604.    
  605.     // java.io.Serializable的写入函数    
  606.     // 将LinkedList的“容量,所有的元素值”都写入到输出流中    
  607.     private void writeObject(java.io.ObjectOutputStream s)    
  608.         throws java.io.IOException {    
  609.         // Write out any hidden serialization magic    
  610.         s.defaultWriteObject();    
  611.    
  612.         // 写入“容量”    
  613.         s.writeInt(size);    
  614.    
  615.         // 将链表中所有节点的数据都写入到输出流中    
  616.         for (Entry e = header.next; e != header; e = e.next)    
  617.             s.writeObject(e.element);    
  618.     }    
  619.    
  620.     // java.io.Serializable的读取函数:依据写入方式反向读出    
  621.     // 先将LinkedList的“容量”读出,然后将“所有的元素值”读出    
  622.     private void readObject(java.io.ObjectInputStream s)    
  623.         throws java.io.IOException, ClassNotFoundException {    
  624.         // Read in any hidden serialization magic    
  625.         s.defaultReadObject();    
  626.    
  627.         // 从输入流中读取“容量”    
  628.         int size = s.readInt();    
  629.    
  630.         // 新建链表表头节点    
  631.         header = new Entry<E>(nullnullnull);    
  632.         header.next = header.previous = header;    
  633.    
  634.         // 从输入流中将“所有的元素值”并逐个加入到链表中    
  635.         for (int i=0; i<size; i++)    
  636.             addBefore((E)s.readObject(), header);    
  637.     }    
  638.    
  639. }   


几点总结

关于LinkedList的源代码,给出几点比較重要的总结:

    1、从源代码中非常明显能够看出,LinkedList的实现是基于双向循环链表的,且头结点中不存放数据,例如以下图;


    2、注意两个不同的构造方法。无參构造方法直接建立一个仅包括head节点的空链表,包括Collection的构造方法,先调用无參构造方法建立一个空链表,而后将Collection中的数据加入到链表的尾部后面。

    3、在查找和删除某元素时,源代码中都划分为该元素为null和不为null两种情况来处理,LinkedList中同意元素为null。

    4、LinkedList是基于链表实现的,因此不存在容量不足的问题。所以这里没有扩容的方法。

    5、注意源代码中的Entry<E> entry(int index)方法。

该方法返回双向链表中指定位置处的节点,而链表中是没有下标索引的,要指定位置出的元素,就要遍历该链表,从源代码的实现中,我们看到这里有一个加速动作

源代码中先将index与长度size的一半比較,假设index<size/2,就仅仅从位置0往后遍历到位置index处。而假设index>size/2,就仅仅从位置size往前遍历到位置index处。这样能够降低一部分不必要的遍历,从而提高一定的效率(实际上效率还是非常低)。

    6、注意链表类相应的数据结构Entry。

例如以下;

  1. // 双向链表的节点所相应的数据结构。    
  2. // 包括3部分:上一节点,下一节点,当前节点值。

        

  3. private static class Entry<E> {    
  4.     // 当前节点所包括的值    
  5.     E element;    
  6.     // 下一个节点    
  7.     Entry<E> next;    
  8.     // 上一个节点    
  9.     Entry<E> previous;    
  10.   
  11.     /**   
  12.      * 链表节点的构造函数。

       

  13.      * 參数说明:   
  14.      *   element  —— 节点所包括的数据   
  15.      *   next      —— 下一个节点   
  16.      *   previous —— 上一个节点   
  17.      */   
  18.     Entry(E element, Entry<E> next, Entry<E> previous) {    
  19.         this.element = element;    
  20.         this.next = next;    
  21.         this.previous = previous;    
  22.     }    
  23. }    
    7、LinkedList是基于链表实现的,因此插入删除效率高,查找效率低(尽管有一个加速动作)
    8、要注意源代码中还实现了栈和队列的操作方法,因此也能够作为栈、队列和双端队列来使用。


Vector源代码剖析


Vector简单介绍

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

    Vector是JDK1.0引入了,它的非常多实现方法都加入了同步语句。因此是线程安全的(事实上也仅仅是相对安全,有些时候还是要加入同步语句来保证线程的安全),能够用于多线程环境。

    Vector没有丝线Serializable接口,因此它不支持序列化,实现了Cloneable接口,能被克隆,实现了RandomAccess接口,支持高速随机訪问。


Vector源代码剖析

    Vector的源代码例如以下(加入了比較具体的凝视):

  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. }   


几点总结

 Vector的源代码实现总体与ArrayList相似。关于Vector的源代码,给出例如以下几点总结:

    1、Vector有四个不同的构造方法。无參构造方法的容量为默认值10,仅包括容量的构造方法则将容量增长量(从源代码中能够看出容量增长量的作用,第二点也会对容量增长量具体说)明置为0。

    2、注意扩充容量的方法ensureCapacityHelper。与ArrayList相同,Vector在每次添加元素(可能是1个,也可能是一组)时,都要调用该方法来确保足够的容量。当容量不足以容纳当前的元素个数时。就先看构造方法中传入的容量增长量參数CapacityIncrement是否为0。假设不为0,就设置新的容量为就容量加上容量增长量。假设为0,就设置新的容量为旧的容量的2倍,假设设置后的新容量还不够,则直接新容量设置为传入的參数(也就是所需的容量),而后相同用Arrays.copyof()方法将元素复制到新的数组。

    3、非常多方法都加入了synchronized同步语句,来保证线程安全。

    4、相同在查找给定元素索引值等的方法中。源代码都将该元素的值分为null和不为null两种情况处理,Vector中也同意元素为null。

    5、其它非常多地方都与ArrayList实现大同小异,Vector如今已经基本不再使用。


注:本集合源代码剖析系列文章转自 http://blog.csdn.net/ns_code 感谢博主!


原文地址:https://www.cnblogs.com/gccbuaa/p/7050256.html