Java 集合系列(二)—— ArrayList

来源:https://www.cnblogs.com/phpstudy2015-6/archive/2019/03/29/10618707.html
-Advertisement-
Play Games

ArrayList ArrayList 是通過一個數組來實現的,因此它是在連續的存儲位置存放對象的引用,只不過它比 Array 更智能,能夠根據集合長度進行自動擴容。 假設讓我們來實現一個簡單的能夠自動擴容的數組,我們最容易想到的點就是: 實際上,ArrayList的內部實現原理也是這樣子,我們可以 ...


ArrayList

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

 

  假設讓我們來實現一個簡單的能夠自動擴容的數組,我們最容易想到的點就是:

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

實際上,ArrayList的內部實現原理也是這樣子,我們可以來研究分析一下ArrayList的源碼

 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     }

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

 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大小,減少在隨機插入操作。

 

優缺點

優點

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

缺陷

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

 

知識腦圖

 

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

 

(以上是自己的一些見解,若有不足或者錯誤的地方請各位指出)

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

 原文地址: https://www.cnblogs.com/phpstudy2015-6/p/10618707.html

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

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • import requests from bs4 import BeautifulSoup from math import ceil header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (... ...
  • 一般公司的項目一般都是用Oracle、Mysql、SQL Server等一些國外的資料庫。前段時間公司做了一個國家政府保密單位的項目,別人要求用國產資料庫,所以研究了下,最後決定用神舟通用的,其實國產也很好幾家做資料庫的還不錯,下邊簡單總結了下,以供參考 1:南大通用 公司簡介 天津南大通用數據技術 ...
  • 題目如下。解題步驟參考的是https://cloud.tencent.com/developer/news/373865中作者的思路。 1.首先,兩個四位數相加等於一個五位數,那麼這個五位數的第一位必定是1,也就是“三”=1,。 2.繼續分析“祥”+“三”,若是“祥”(8),“三”為1,那麼低位必定 ...
  • JDBC的使用流程,通過JDBC進行對資料庫增刪改查的操作及代碼封裝。 ...
  • 題意 "題目鏈接" Sol 我們可以把圖行列拆開,同時對於行/列拆成很多個聯通塊,然後考慮每個點所在的行聯通塊/列聯通塊的貢獻。 可以這樣建邊 從S向每個行聯通塊連聯通塊大小條邊,每條邊的容量為1,費用為$i$(i表示這是第幾條邊)。 從每個點所在的行聯通塊向列聯通塊連邊,容量為1,費用為0 從每個 ...
  • 想要熟練使用PyQt,還是需要深入研究下這個庫的使用,筆者這裡只是拋磚引玉。 關註公眾號「**Python專欄**」,後臺回覆:**zsxq06**,獲取本文全套代碼。 ...
  • python讀取大文件 1. 較pythonic的方法,使用with結構 文件可以自動關閉 異常可以在with塊內處理 <! more 最大的優點 :對可迭代對象 f,進行迭代遍歷:for line in f,會自動地使用緩衝IO(buffered IO)以及記憶體管理,而不必擔心任何大文件的問題。 ...
  • 一、簡要說明 開篇說明 其實吧這是我人生中寫的第一篇博客,我也不知道怎麼排版和編輯讓博文顯示的更加美觀,現在正在學Markdown編輯語法,也是剛剛學編程的一個小菜鳥,目前是大二的在校生,我的初衷是把我平時所學的知識都像做筆記一樣寫下來,讓以後在學習更多知識的時候回來一看,舊的知識就可以鞏固回來了, ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...