Java容器——ArrayList(Java8 )源碼解析

    ArrayList是一種常用List類型實現,也是Java集合中的的常用類型,以遍歷查詢性能優異著稱,繼承關係如下:

    可見ArrayList實現了Cloneable,Serializable,RandomAcess和List接口,繼承了AbstractList抽象類,簡而言之,ArrayList是一個實現了可複製,可序列化,支持快速隨機訪問的List類型。這裏最重要的是實現了List的接口,包括初始化,新增,查詢,刪除,銷燬等函數,具體如何實現,請見下文分析。

      一 類成員變量

     /**
     * List默認初始化長度
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 存儲ArrayList數據的數組
     */
    transient Object[] elementData;

    /**
     * List的實際長度
     */
    private int size;

    /**
     * ArrayList最大長度
     */
  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    

    這裏列出了三個重要的變量,具體釋義見註釋。ArrayList在初始化時默認爲空的數組,當首個元素加入到List中時,長度擴容到10。size是數組的實際容量,也即是List的大小,初始化爲0。elementData是Object類型的數組,也是實際存放數據的數組。以Object作爲數組元素使得List可以有效支持泛型。這裏有一點需要注意,既然elementData用來存放元素,那爲何不使用elementData.length而是使用size這一變量作爲ArrayList的長度呢?在下文中會結合使用進行說明。

    二 函數解析

     1 構造函數 

  /**                                                                               
   * Constructs an empty list with the specified initial capacity.                  
   *                                                                                
   * @param  initialCapacity  the initial capacity of the list                      
   * @throws IllegalArgumentException if the specified initial capacity             
   *         is negative                                                            
   */                                                                               
  public ArrayList(int initialCapacity) {                                           
      if (initialCapacity > 0) {                                                    
          this.elementData = new Object[initialCapacity];                           
      } else if (initialCapacity == 0) {                                            
          this.elementData = EMPTY_ELEMENTDATA;                                     
      } else {                                                                      
          throw new IllegalArgumentException("Illegal Capacity: "+                  
                                             initialCapacity);                      
      }                                                                             
  }                                                                                 
                                                                                    
  /**                                                                               
   * Constructs an empty list with an initial capacity of ten.                      
   */                                                                               
  public ArrayList() {                                                              
      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;                         
  }                                                                                 
                                                                                    
  /**                                                                               
   * Constructs a list containing the elements of the specified                     
   * collection, in the order they are returned by the collection's                 
   * iterator.                                                                      
   *                                                                                
   * @param c the collection whose elements are to be placed into this list         
   * @throws NullPointerException if the specified collection is null               
   */                                                                               
  public ArrayList(Collection<? extends E> c) {                                     
      elementData = c.toArray();                                                    
      if ((size = elementData.length) != 0) {                                       
          // defend against c.toArray (incorrectly) not returning Object[]          
          // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)            
          if (elementData.getClass() != Object[].class)                             
              elementData = Arrays.copyOf(elementData, size, Object[].class);       
      } else {                                                                      
          // replace with empty array.                                              
          this.elementData = EMPTY_ELEMENTDATA;                                     
      }                                                                             
  }                                                                                 

    構造函數有三個:

  •     無參構造函數:elementData初始化爲空數組,此時size默認爲0。
  •    初始化長度構造函數:elementData擴容爲指定長度的未初始化數組。注意這裏size並沒有被設置爲指定長度,此時elementData.length和size是不一致的。實際上elementData.length表示當前ArrayList的最大容量,而size則表示了實際存放元素的個數。
  •    容器初始化函數:通過容器已有數據構造ArrayList。

   2 增加元素


 
 /**                                                                          
  * Inserts the specified element at the specified position in this           
  * list. Shifts the element currently at that position (if any) and          
  * any subsequent elements to the right (adds one to their indices).         
  *                                                                           
  * @param index index at which the specified element is to be inserted       
  * @param element element to be inserted                                     
  * @throws IndexOutOfBoundsException {@inheritDoc}                           
  */                                                                          
 public void add(int index, E element) {                                      
     rangeCheckForAdd(index);                                                 
     modCount++;                                                              
     final int s;                                                             
     Object[] elementData;                                                    
     if ((s = size) == (elementData = this.elementData).length)               
         elementData = grow();                                                
     System.arraycopy(elementData, index,                                     
                      elementData, index + 1,                                 
                      s - index);                                             
     elementData[index] = element;                                            
     size = s + 1;                                                            
 }                                                                     

    add函數重載的包括多個,這裏只列出一個具有代表性的進行說明,其他的add方法可由它推演而來。這個函數做了這麼幾件事,首先檢查要插入的下標是否越界,是的話直接拋異常退出。然後檢查elementData.length和size是否一致,一致說明容量已滿,需要擴容,增加一個元素的容量。將index之後的元素分別拷貝到原下標+1的位置,將index位置設爲指定element,並將ArrayList的實際長度加一。

    這一步驟的關鍵,或者說ArrayList的關鍵,在於擴容,來看一下擴容的實現。

   /**                                                                    
    * Increases the capacity to ensure that it can hold at least the      
    * number of elements specified by the minimum capacity argument.      
    *                                                                     
    * @param minCapacity the desired minimum capacity                     
    * @throws OutOfMemoryError if minCapacity is less than zero           
    */                                                                    
   private Object[] grow(int minCapacity) {                               
       return elementData = Arrays.copyOf(elementData,                    
                                          newCapacity(minCapacity));      
   }                                                                      
                                                                          
   private Object[] grow() {                                              
       return grow(size + 1);                                             
   }                                                                      
                                                                          
   /**                                                                    
    * Returns a capacity at least as large as the given minimum capacity. 
    * Returns the current capacity increased by 50% if that suffices.     
    * Will not return a capacity greater than MAX_ARRAY_SIZE unless       
    * the given minimum capacity is greater than MAX_ARRAY_SIZE.          
    *                                                                     
    * @param minCapacity the desired minimum capacity                     
    * @throws OutOfMemoryError if minCapacity is less than zero           
    */                                                                    
   private int newCapacity(int minCapacity) {                             
       // overflow-conscious code                                         
       int oldCapacity = elementData.length;                              
       int newCapacity = oldCapacity + (oldCapacity >> 1);                
       if (newCapacity - minCapacity <= 0) {                              
           if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)          
               return Math.max(DEFAULT_CAPACITY, minCapacity);            
           if (minCapacity < 0) // overflow                               
               throw new OutOfMemoryError();                              
           return minCapacity;                                            
       }                                                                  
       return (newCapacity - MAX_ARRAY_SIZE <= 0)                         
           ? newCapacity                                                  
           : hugeCapacity(minCapacity);      
   }                             

    當ArrayList容量不夠時,默認需要增加一個元素的長度。在實際執行過程中,是擴容到之前容量的1.5倍,然後判斷是否超過最大限制,超過則報內存溢出錯誤。在擴容過程中,最大不得超過MAX_ARRAY_SIZE,即ArrayList的最大長度。

    由此可見,向ArrayList插入元素時,當元素個數小於實際容量大小時,只要進行部分數組的拷貝工作,容量已滿時,需要擴容則要將ArrayList的所有元素拷貝到新建數組中,這個步驟是比較耗時的。元素的插入確實不是ArrayList的強項。

3 查詢,修改元素

    查詢和修改實際是通過下標來訪問和修改數組元素,時間複雜度只有O(1),相對於LinkedList和其他容器,都具有絕對的速度優勢。

   /**                                                                                  
    * Returns the element at the specified position in this list.                       
    *                                                                                   
    * @param  index index of the element to return                                      
    * @return the element at the specified position in this list                        
    * @throws IndexOutOfBoundsException {@inheritDoc}                                   
    */                                                                                  
   public E get(int index) {                                                            
       Objects.checkIndex(index, size);                                                 
       return elementData(index);                                                       
   }                                                                                    
                                                                                        
   /**                                                                                  
    * Replaces the element at the specified position in this list with                  
    * the specified element.                                                            
    *                                                                                   
    * @param index index of the element to replace                                      
    * @param element element to be stored at the specified position                     
    * @return the element previously at the specified position                          
    * @throws IndexOutOfBoundsException {@inheritDoc}                                   
    */                                                                                  
   public E set(int index, E element) {                                                 
       Objects.checkIndex(index, size);                                                 
       E oldValue = elementData(index);                                                 
       elementData[index] = element;                                                    
       return oldValue;                                                                 
   }                                                                                    
                                                                                        

    只是進行下標檢測,獲取或者替換指定index位置的元素。

4 刪除元素,銷燬

    刪除元素對ArrayList來說也有一定的工作量,需要將指定index位置以後的元素統統向前移位,如果ArrayList較長且刪除元素的位置靠前,這就是一個比較耗時的操作了。

   /**                                                                                
    * Removes the element at the specified position in this list.                     
    * Shifts any subsequent elements to the left (subtracts one from their            
    * indices).                                                                       
    *                                                                                 
    * @param index the index of the element to be removed                             
    * @return the element that was removed from the list                              
    * @throws IndexOutOfBoundsException {@inheritDoc}                                 
    */                                                                                
   public E remove(int index) {                                                       
       Objects.checkIndex(index, size);                                               
                                                                                      
       modCount++;                                                                    
       E oldValue = elementData(index);                                               
                                                                                      
       int numMoved = size - index - 1;                                               
       if (numMoved > 0)                                                              
           System.arraycopy(elementData, index+1, elementData, index,                 
                            numMoved);                                                
       elementData[--size] = null; // clear to let GC do its work                                                                                              
       return oldValue;                                                               
   }                                                                                  

    這裏還需要注意,實際上,刪除元素時,並沒有新建一個數組將原數組拷貝進去,而拷貝元素後將原先末尾的位置置爲null並且減小size。這裏再提出一個問題,將數組元素的最後一位設爲null後,虛擬機會對該位置進行垃圾回收嗎,數組的實際長度變化了嗎?

    最後看ArrayList的銷燬。

  /**                                                              
   * Removes all of the elements from this list.  The list will    
   * be empty after this call returns.                             
   */                                                              
  public void clear() {                                            
      modCount++;                                                  
      final Object[] es = elementData;                             
      for (int to = size, i = size = 0; i < to; i++)               
          es[i] = null;                                            
  }                                                                

    銷燬比較簡單,只是把數組各元素置爲null,並且將size設爲0。

    小結

   容器最重要的功能是存儲和獲取元素,本文從源碼角度介紹了ArrayList的增刪改查和原理,ArrayList還有一些其他未提到的特性,將在後面的文章中展示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章