Java 集合系列(二)—— ArrayList

ArrayList

  ArrayList 是經過一個數組來實現的,所以它是在連續的存儲位置存放對象的引用,只不過它比 Array 更智能,可以根據集合長度進行自動擴容。php

 

  假設讓咱們來實現一個簡單的可以自動擴容的數組,咱們最容易想到的點就是:html

  1. add()的時候須要判斷當前數組size+1是否等於此時定義的數組大小;
  2. 若小於直接添加便可;不然,須要先擴容再進行添加。

實際上,ArrayList的內部實現原理也是這樣子,咱們能夠來研究分析一下ArrayList的源碼git

 add(E e) 源碼分析

 1   /**
 2  * Appends the specified element to the end of this list.  3  *  4  * @param e element to be appended to this list  5  * @return <tt>true</tt> (as specified by {@link Collection#add})  6      */
 7     public boolean add(E e) {  8         ensureCapacityInternal(size + 1);   // 進行擴容校驗
 9         elementData[size++] = e;            // 將值添加到數組後面,並將 size+1
10         return true; 11  } 12 
13 
14 
15     /**
16  * The array buffer into which the elements of the ArrayList are stored. 17  * The capacity of the ArrayList is the length of this array buffer. Any 18  * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 19  * will be expanded to DEFAULT_CAPACITY when the first element is added. 20      */
21     transient Object[] elementData; // non-private to simplify nested class access
22     
23     private void ensureCapacityInternal(int minCapacity) { 24         ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));    // elementData 數組
25  } 26 
27 
28 
29     /**
30  * Default initial capacity. 31      */
32     private static final int DEFAULT_CAPACITY = 10; 33     
34     /**
35  * Shared empty array instance used for default sized empty instances. We 36  * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when 37  * first element is added. 38      */
39     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; 40 
41     // 返回最大的 index
42     private static int calculateCapacity(Object[] elementData, int minCapacity) { 43         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {   // 與空數組實例對比
44             return Math.max(DEFAULT_CAPACITY, minCapacity); 45  } 46         return minCapacity; 47  } 48 
49 
50 
51     private void ensureExplicitCapacity(int minCapacity) { 52         modCount++; 53 
54         // overflow-conscious code
55         if (minCapacity - elementData.length > 0) 56  grow(minCapacity); 57     }

擴容調用方法,實際也就是數組複製的過程github

 1     /**
 2  * Increases the capacity to ensure that it can hold at least the  3  * number of elements specified by the minimum capacity argument.  4  *  5  * @param minCapacity the desired minimum capacity  6      */
 7     private void grow(int minCapacity) {  8         // overflow-conscious code
 9         int oldCapacity = elementData.length; 10         int newCapacity = oldCapacity + (oldCapacity >> 1); 11         if (newCapacity - minCapacity < 0) 12             newCapacity = minCapacity; 13         if (newCapacity - MAX_ARRAY_SIZE > 0) 14             newCapacity = hugeCapacity(minCapacity); 15         // minCapacity is usually close to size, so this is a win:
16         elementData = Arrays.copyOf(elementData, newCapacity); 17     }

 add(int index, E element) 源碼分析

 1   /**
 2  * Inserts the specified element at the specified position in this  3  * list. Shifts the element currently at that position (if any) and  4  * any subsequent elements to the right (adds one to their indices).  5  *  6  * @param index index at which the specified element is to be inserted  7  * @param element element to be inserted  8  * @throws IndexOutOfBoundsException {@inheritDoc}  9      */
10     public void add(int index, E element) { 11         rangeCheckForAdd(index);    // 校驗index是否超過當前定義的數組大小範圍,超過則拋出 IndexOutOfBoundsException
12 
13         ensureCapacityInternal(size + 1);  // Increments modCount!!
14         System.arraycopy(elementData, index, elementData, index + 1, 15                          size - index);     // 複製,向後移動
16         elementData[index] = element; 17         size++; 18  } 19     
20 
21     /**
22  * A version of rangeCheck used by add and addAll. 23      */
24     private void rangeCheckForAdd(int index) { 25         if (index > size || index < 0) 26             throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 27     }

從上面的源碼分析可知,擴容和隨機插入元素的消耗比較大,所以在實際開發中,應儘可能指定ArrayList大小,減小在隨機插入操做。數組

 

優缺點

優勢app

  • 封裝了一個動態再分配的對象數組
  • 使用索引進行隨機訪問效率高

缺陷源碼分析

  • 在數組中增刪一個元素,全部元素都要日後往前移動,效率低下

 

知識腦圖

 

在 github 上建了一個 repository ,Java Core Knowledge Tree,各位看官如果喜歡請給個star,以示鼓勵,謝謝。
https://github.com/suifeng412/JCKTree學習

 

(以上是本身的一些看法,如有不足或者錯誤的地方請各位指出)ui

 做者:那一葉隨風   http://www.cnblogs.com/phpstudy2015-6/this

 原文地址: http://www.javashuo.com/article/p-wpafiemz-co.html

 聲明:本博客文章爲原創,只表明本人在工做學習中某一時間內總結的觀點或結論。轉載時請在文章頁面明顯位置給出原文連接

 

原文出處:https://www.cnblogs.com/phpstudy2015-6/p/10618707.html

相關文章
相關標籤/搜索