ArrayList源码分析

来源:互联网 发布:圆方软件论坛 编辑:程序博客网 时间:2024/06/10 21:09
  1. /**
     * AbstractList提供了List接口的默认实现(个别方法为抽象方法)。
     * List接口定义了列表必须实现的方法。
     * RandomAccess是一个标记接口,接口内没有定义任何内容。
     * 实现了Cloneable接口的类,可以调用Object.clone方法返回该对象的浅拷贝。
     * 通过实现 java.io.Serializable 接口以启用其序列化功能。
     * 未实现此接口的类将无法使其任何状态序列化或反序列化。序列化接口没有方法或字段,仅用于标识可序列化的语义。
     * @author Time
     *
     */
  1. package java.util;    
  1. public class ArrayList<E> extends AbstractList<E>    
  2.         implements List<E>, RandomAccess, Cloneable, java.io.Serializable    
  3. {    
  4.     // 序列版本号    
  5.     private static final long serialVersionUID = 8683452581122892189L;    
  6.    
  7.     // ArrayList基于该数组实现,用该数组保存数据   

  8.     private transient Object[] elementData;    
  9.    
  10.     // ArrayList中实际数据的数量    
  11.     private int size;    
  12.    
  13.     // ArrayList带容量大小的构造函数。    
  14.     public ArrayList(int initialCapacity) {    
  15.         super();    
  16.         if (initialCapacity < 0)    
  17.             throw new IllegalArgumentException("Illegal Capacity: "+    
  18.                                                initialCapacity);    
  19.         // 新建一个数组    
  20.         this.elementData = new Object[initialCapacity];    
  21.     }    
  22.    
  23.     // ArrayList无参构造函数。默认容量是10。    
  24.     public ArrayList() {    
  25.         this(10);    
  26.     }    
  27. // 创建一个包含collection的ArrayList,  将提供的集合转成数组返回给elementData(返回若不是Object[]将调用Arrays.copy方法将其转为Object[])。    
  28.  public ArrayList(Collection<? extends E> c) {    
  29.         elementData = c.toArray();    
  30.         size = elementData.length;    
  31.         if (elementData.getClass() != Object[].class)    
  32.             elementData = Arrays.copyOf(elementData, size, Object[].class);    
  33.     }    

  34.    
  35.     // 将当前容量值设为实际元素个数    
  36.     public void trimToSize() {    
  37.         modCount++;    
  38.         int oldCapacity = elementData.length;    
  39.         if (size < oldCapacity) {    
  40.             elementData = Arrays.copyOf(elementData, size);    
  41.         }    
  42.     }    
  43.    
  44.    
  45.     // 确定ArrarList的容量。    
  46.     // 若ArrayList的容量不足以容纳当前的全部元素,设置 新的容量=“(原始容量x3)/2 + 1”    
  47.     public void ensureCapacity(int minCapacity) {    
  48.         // 将“修改统计数”+1,该变量主要是用来实现fail-fast机制的    
  49.         modCount++;    
  50.         int oldCapacity = elementData.length;    
  51.         // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”    
  52.         if (minCapacity > oldCapacity) {    
  53.             Object oldData[] = elementData;    
  54.             int newCapacity = (oldCapacity * 3)/2 + 1;    
  55.             //如果还不够,则直接将minCapacity设置为当前容量  
  56.             if (newCapacity < minCapacity)    
  57.                 newCapacity = minCapacity;    
  58.             elementData = Arrays.copyOf(elementData, newCapacity);    
  59.         }    
  60.     }    
  61.    
  62.     // 添加元素e    
  63.     public boolean add(E e) {    
  64.         // 确定ArrayList的容量大小    
  65.         ensureCapacity(size + 1);  // Increments modCount!!    
  66.         // 添加e到ArrayList中    
  67.         elementData[size++] = e;    
  68.         return true;    
  69.     }    
  70.    
  71.     // 返回ArrayList的实际大小    
  72.     public int size() {    
  73.         return size;    
  74.     }    
  75.    
  76.     // ArrayList是否包含Object(o)    
  77.     public boolean contains(Object o) {    
  78.         return indexOf(o) >= 0;    
  79.     }    
  80.    
  81.     //返回ArrayList是否为空    
  82.     public boolean isEmpty() {    
  83.         return size == 0;    
  84.     }    
  85.    
  86.     // 正向查找,返回元素的索引值    
  87.     public int indexOf(Object o) {    
  88.         if (o == null) {    
  89.             for (int i = 0; i < size; i++)    
  90.             if (elementData[i]==null)    
  91.                 return i;    
  92.             } else {    
  93.                 for (int i = 0; i < size; i++)    
  94.                 if (o.equals(elementData[i]))    
  95.                     return i;    
  96.             }    
  97.             return -1;    
  98.         }         
  99.    
  100.     // 反向查找(从数组末尾向开始查找),返回元素(o)的索引值    
  101.     public int lastIndexOf(Object o) {    
  102.         if (o == null) {    
  103.             for (int i = size-1; i >= 0; i--)    
  104.             if (elementData[i]==null)    
  105.                 return i;    
  106.         } else {    
  107.             for (int i = size-1; i >= 0; i--)    
  108.             if (o.equals(elementData[i]))    
  109.                 return i;    
  110.         }    
  111.         return -1;    
  112.     }    
  113.      
  114.    
  115.     // 返回ArrayList的Object数组    
  116.     public Object[] toArray() {    
  117.         return Arrays.copyOf(elementData, size);    
  118.     }    
  119.    
  120.     // 返回ArrayList元素组成的数组  
  121.     public <T> T[] toArray(T[] a) {    
  122.         // 若数组a的大小 < ArrayList的元素个数;    
  123.         // 则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中    
  124.         if (a.length < size)    
  125.             return (T[]) Arrays.copyOf(elementData, size, a.getClass());    
  126.    
  127.         // 若数组a的大小 >= ArrayList的元素个数;    
  128.         // 则将ArrayList的全部元素都拷贝到数组a中。    
  129.         System.arraycopy(elementData, 0, a, 0, size);    
  130.         if (a.length > size)    
  131.             a[size] = null;    
  132.         return a;    
  133.     }    
  134.    
  135.     // 获取index位置的元素值    
  136.     public E get(int index) {    
  137.         RangeCheck(index);    
  138.    
  139.         return (E) elementData[index];    
  140.     }    
  141.    
  142.     // 设置index位置的值为element    
  143.     public E set(int index, E element) {    
  144.         RangeCheck(index);    
  145.    
  146.         E oldValue = (E) elementData[index];    
  147.         elementData[index] = element;    
  148.         return oldValue;    
  149.     }    
  150.    
  151.     // 将e添加到ArrayList中    
  152.     public boolean add(E e) {    
  153.         ensureCapacity(size + 1);  // Increments modCount!!    
  154.         elementData[size++] = e;    
  155.         return true;    
  156.     }    
  157.    
  158.     // 将e添加到ArrayList的指定位置    
  159.     public void add(int index, E element) {    
  160.         if (index > size || index < 0)    
  161.             throw new IndexOutOfBoundsException(    
  162.             "Index: "+index+", Size: "+size);    
  163.    
  164.         ensureCapacity(size+1);  // Increments modCount!!           
  165.         System.arraycopy(elementData, index, elementData, index + 1,    
  166.              size - index);    
  167.         elementData[index] = element;    
  168.         size++;    
  169.     }    
  170. // 首先判断指定位置index是否超出elementData的界限,之后调用ensureCapacity调整容量(若容量足够则不会拓展),调用System.arraycopy将elementData从index开始的size-index个元素复制到index+1至size+1的位置(即index开始的元素都向后移动一个位置),然后将index位置的值指向element。
  171.     // 删除ArrayList指定位置的元素    
  172.     public E remove(int index) {    
  173.         RangeCheck(index);    
  174.    
  175.         modCount++;    
  176.         E oldValue = (E) elementData[index];    
  177.    
  178.         int numMoved = size - index - 1;    
  179.         if (numMoved > 0)    
  180.             System.arraycopy(elementData, index+1, elementData, index,    
  181.                  numMoved);    
  182.         elementData[--size] = null// Let gc do its work    
  183.    
  184.         return oldValue;    
  185.     }    
  186.    
  187.     // 删除ArrayList的指定元素    
  188.     public boolean remove(Object o) {    
  189.         if (o == null) {    
  190.                 for (int index = 0; index < size; index++)    
  191.             if (elementData[index] == null) {    
  192.                 fastRemove(index);    
  193.                 return true;    
  194.             }    
  195.         } else {    
  196.             for (int index = 0; index < size; index++)    
  197.             if (o.equals(elementData[index])) {    
  198.                 fastRemove(index);    
  199.                 return true;    
  200.             }    
  201.         }    
  202.         return false;    
  203.     }    
  204.    
  205.    
  206.     // 快速删除第index个元素    
  207.     private void fastRemove(int index) {    
  208.         modCount++;    
  209.         int numMoved = size - index - 1;    
  210.         // 从"index+1"开始,用后面的元素替换前面的元素。    
  211.         if (numMoved > 0)    
  212.             System.arraycopy(elementData, index+1, elementData, index,    
  213.                              numMoved);    
  214.         // 将最后一个元素设为null    
  215.         elementData[--size] = null// Let gc do its work    
  216.     }    
  217.    
  218.     // 删除元素    
  219.     public boolean remove(Object o) {    
  220.         if (o == null) {    
  221.             for (int index = 0; index < size; index++)    
  222.             if (elementData[index] == null) {    
  223.                 fastRemove(index);    
  224.             return true;    
  225.             }    
  226.         } else {    
  227.             // 便利ArrayList,找到“元素o”,则删除,并返回true。    
  228.             for (int index = 0; index < size; index++)    
  229.             if (o.equals(elementData[index])) {    
  230.                 fastRemove(index);    
  231.             return true;    
  232.             }    
  233.         }    
  234.         return false;    
  235.     }    
  236.    
  237.     // 清空ArrayList,将全部的元素设为null    
  238.     public void clear() {    
  239.         modCount++;    
  240.    
  241.         for (int i = 0; i < size; i++)    
  242.             elementData[i] = null;    
  243.    
  244.         size = 0;    
  245.     }    
  246.    
  247. // 将集合c追加到ArrayList中  
  248. //先将集合c转换成数组,根据转换后数组的程度和ArrayList的size拓展容量,之后调用System.arraycopy方法复制元素到elementData的尾部,调整size。根据返回的内容分析,只要集合c的大小不为空,即转换后的数组长度不为0则返回true。 
  249.     public boolean addAll(Collection<? extends E> c) {    
  250.         Object[] a = c.toArray();    
  251.         int numNew = a.length;    
  252.         ensureCapacity(size + numNew);  // Increments modCount    
  253.         System.arraycopy(a, 0, elementData, size, numNew);    
  254.         size += numNew;    
  255.         return numNew != 0;    
  256.     }    
  257.    
  258.     // 从index位置开始,将集合c添加到ArrayList    
  259.     public boolean addAll(int index, Collection<? extends E> c) {    
  260.         if (index > size || index < 0)    
  261.             throw new IndexOutOfBoundsException(    
  262.             "Index: " + index + ", Size: " + size);    
  263.    
  264.         Object[] a = c.toArray();    
  265.         int numNew = a.length;    
  266.         ensureCapacity(size + numNew);  // Increments modCount    
  267.    
  268.         int numMoved = size - index;    
  269.         if (numMoved > 0)    
  270.             System.arraycopy(elementData, index, elementData, index + numNew,    
  271.                  numMoved);    
  272.    
  273.         System.arraycopy(a, 0, elementData, index, numNew);    
  274.         size += numNew;    
  275.         return numNew != 0;    
  276.     }    
  277.    
  278.     // 删除fromIndex到toIndex之间的全部元素。    
  279.     protected void removeRange(int fromIndex, int toIndex) {    
  280.     modCount++;    
  281.     int numMoved = size - toIndex;    
  282.         System.arraycopy(elementData, toIndex, elementData, fromIndex,    
  283.                          numMoved);    
  284.    
  285.     // Let gc do its work    
  286.     int newSize = size - (toIndex-fromIndex);    
  287.     while (size != newSize)    
  288.         elementData[--size] = null;    
  289.     }    
  290.    
  291.     private void RangeCheck(int index) {    
  292.     if (index >= size)    
  293.         throw new IndexOutOfBoundsException(    
  294.         "Index: "+index+", Size: "+size);    
  295.     }    
  296.    
  297.    
  298.     // 克隆函数    
  299.     public Object clone() {    
  300.         try {    
  301.             ArrayList<E> v = (ArrayList<E>) super.clone();    
  302.             // 将当前ArrayList的全部元素拷贝到v中    
  303.             v.elementData = Arrays.copyOf(elementData, size);    
  304.             v.modCount = 0;    
  305.             return v;    
  306.         } catch (CloneNotSupportedException e) {    
  307.             // this shouldn't happen, since we are Cloneable    
  308.             throw new InternalError();    
  309.         }    
  310.     }    
  311.    
  312.    
  313.     // java.io.Serializable的写入函数    
  314.     // 将ArrayList的“容量,所有的元素值”都写入到输出流中    
  315.     private void writeObject(java.io.ObjectOutputStream s)    
  316.         throws java.io.IOException{    
  317.     // Write out element count, and any hidden stuff    
  318.     int expectedModCount = modCount;    
  319.     s.defaultWriteObject();    
  320.    
  321.         // 写入“数组的容量”    
  322.         s.writeInt(elementData.length);    
  323.    
  324.     // 写入“数组的每一个元素”    
  325.     for (int i=0; i<size; i++)    
  326.             s.writeObject(elementData[i]);    
  327.    
  328.     if (modCount != expectedModCount) {    
  329.             throw new ConcurrentModificationException();    
  330.         }    
  331.    
  332.     }    
  333.    
  334.    
  335.     // java.io.Serializable的读取函数:根据写入方式读出    
  336.     // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出    
  337.     private void readObject(java.io.ObjectInputStream s)    
  338.         throws java.io.IOException, ClassNotFoundException {    
  339.         // Read in size, and any hidden stuff    
  340.         s.defaultReadObject();    
  341.    
  342.         // 从输入流中读取ArrayList的“容量”    
  343.         int arrayLength = s.readInt();    
  344.         Object[] a = elementData = new Object[arrayLength];    
  345.    
  346.         // 从输入流中将“所有的元素值”读出    
  347.         for (int i=0; i<size; i++)    
  348.             a[i] = s.readObject();    
  349.     }    
  350. }  
原创粉丝点击