《Java 高階篇》五:資料結構

ACatSmiling發表於2024-10-02

Author: ACatSmiling

Since: 2024-10-01

概述

在 Java 語言中,陣列(Array)和集合都是對多個資料進行儲存操作的結構,簡稱Java 容器。此時的儲存,主要指的是記憶體層面的儲存,不涉及到持久化的儲存。

陣列在記憶體儲存方面的特點:

  • 陣列一旦初始化以後,其長度就確定了。
  • 陣列一旦定義好,其元素的型別也就確定了。

陣列在儲存資料方面的弊端:

  • 陣列一旦初始化以後,其長度就不可修改,不便於擴充套件。
  • 陣列中提供的屬性和方法少,不便於進行新增、刪除、插入等操作,且效率不高。
  • 陣列中沒有現成的屬性和方法,去直接獲取陣列中已儲存的元素的個數(只能直接知道陣列的長度)。
  • 陣列儲存的資料是有序的、可重複的。對於無序、不可重複的需求,不能滿足,即陣列儲存資料的特點比較單一。

Java 集合類可以用於儲存數量不等的多個物件,還可用於儲存具有對映關係的關聯陣列。

Java 集合框架可分為CollectionMap兩種體系:

  • Collection 介面 :單列集合,用來儲存一個一個的物件。
    • List 介面:儲存有序的、可重複的資料。包括:ArrayList、LinkedList、Vector。
    • Set 介面:儲存無序的、不可重複的資料。包括:HashSet、LinkedHashSet、TreeSet。
  • Map 介面:雙列集合,用來儲存具有對映關係 "key - value 對" 的資料。包括:HashMap、LinkedHashMap、TreeMap、Hashtable、Properties。

陣列

**陣列(Array)**,是多個相同型別的資料按一定順序排列的集合,使用一個名字命名,並透過編號的方式對這些資料進行統一管理。

陣列的相關概念:

  • 陣列名
  • 元素
  • 下標/索引
  • 陣列的長度

陣列的特點:

  • 陣列是有序排列的。
  • 建立陣列物件會在記憶體中開闢一整塊連續的空間,而陣列名中引用的是這塊連續空間的首地址。
  • 陣列本身是引用資料型別的變數,但陣列中的元素可以是任何資料型別,既可以是基本資料型別,也可以是引用資料型別。
  • 可以直接透過下標/索引的方式呼叫指定位置的元素,速度很快。
  • 陣列的長度一旦確定,就不能修改。

陣列的分類:

  • 按照維度:一維陣列、二維陣列、三維陣列、…
  • 按照元素的資料型別分:基本資料型別元素的陣列、引用資料型別元素的陣列(即物件陣列)。

一維陣列

宣告方式:type var[] 或 type[] var;。例如:

int a[];
int[] a1;
double b[];
String[] c;// 引用型別變數陣列

不同寫法:int[] x;int x[];

Java 語言中宣告陣列時,不能指定其長度(陣列中元素的數), 例如:int a[5];// 非法

public static void main(String[] args) {
    // 1-1 靜態初始化,方式一
    int[] ids = new int[]{1001, 1002, 1003, 1004, 1005};
    
    // 1-2 靜態初始化,方式二,型別推斷
    int[] ids2 = {1001, 1002, 1003, 1004, 1005};

    // 2 動態初始化
    String[] names = new String[5];
    names[0] = "Student A";
    names[1] = "Student B";
    names[2] = "Student C";
    names[3] = "Student D";
    names[4] = "Student E";

    // 3 陣列的長度
    System.out.println("ids 的長度:" + ids.length);// 5
    System.out.println("names 的長度:" + names.length);// 5

    // 4 遍歷陣列
    for (int i = 0; i < ids.length; i++) {
        System.out.println(ids[i]);
    }

    for (int i = 0; i < names.length; i++) {
        System.out.println(names[i]);
    }

    // 5 簡寫方式遍歷陣列
    for (int id : ids) {
        System.out.println(id);
    }

    for (String name : names) {
        System.out.println(name);
    }

    // 6 陣列元素的預設初始化值
    int[] arrs = new int[5];
    for (int arr : arrs) {
        System.out.println(arr);// 0
    }

    String[] arrs2 = new String[5];
    for (String arr2 : arrs2) {
        System.out.println(arr2);// null
    }
}
  • 靜態初始化:陣列的初始化,和陣列元素的賦值操作同時進行,如:"int[] ids = new int[]{1001, 1002, 1003, 1004, 1005};"。

  • 動態初始化 :陣列的初始化,和陣列元素的賦值操作分開進行,如:"String[] names = new String[5]; names[1] = "a";"。

  • 定義陣列並用運算子 new 為之分配空間後,才可以引用陣列中的每個元素。

  • 陣列元素的引用方式:陣列名[陣列元素下標]

  • 陣列元素下標從 0 開始,長度為 n 的陣列的合法下標取值範圍:0 ~ n - 1。如:int a[] = new int[3];,則可引用的陣列元素為 a[0]、a[1] 和 a[2]。

  • 陣列元素下標可以是整型常量或整型表示式。如 a[3],b[i],c[6*i]。

  • 陣列一旦初始化完成,其長度也隨即確定,且長度不可變。每個陣列都有一個屬性 length 指明它的長度,例如:a.length 指明陣列 a 的長度(元素個數)。

  • 陣列是引用型別,它的元素相當於類的成員變數,因此陣列一經分配空間,其中的每個元素也被按照成員變數同樣的方式被隱式初始化。然後,再根據實際程式碼設定,將陣列相應位置的元素進行賦值,即顯示賦值

    陣列元素型別 元素預設初始值
    byte 0
    short 0
    int 0
    long 0L
    float 0.0F
    double 0.0
    char 0 或寫為 '\u000' (表現為空)
    boolean false
    引用型別 null
    • 對於基本資料型別而言,預設的初始化值各有不同;對於引用資料型別而言,預設的初始化值為 null。
    • char 型別的預設值是 0,不是 '0',表現的是類似空格的一種效果。

二維陣列

Java 語言裡提供了支援多維陣列的語法。如果把一維陣列當成幾何中的線性圖形,那麼二維陣列就相當於是一個表格。

對於二維陣列的理解,可以看成是一維陣列 array1,作為另一個一維陣列 array2 的元素而存在。其實,從陣列底層的執行機制來看,沒有多維陣列。

  • 可以理解為,array2 是外層陣列,array1 則是外層陣列每一個位置上的值,即內層陣列。

不同寫法:int[][] x;int[] x[];int x[][];

public static void main(String[] args) {
    // 1-1 靜態初始化,方式一
    int[][] arr = new int[][]{{3, 8, 2}, {2, 7}, {9, 0, 1, 6}};

    // 1-2 靜態初始化,方式二,型別推斷
    int[][] arr2 = {{3, 8, 2}, {2, 7}, {9, 0, 1, 6}};
    System.out.println(arr2[2][3]);

    // 2-1 動態初始化,方式一
    /*
    定義了名稱為 arr3 的二維陣列,二維陣列中有 3 個一維陣列,內層每一個一維陣列中有 2 個元素
    內層一維陣列的名稱分別為 arr3[0],arr3[1],arr3[2],返回的是地址值
    給內層第一個一維陣列 1 腳標位賦值為 78 寫法是:arr3[0][1] = 78;
     */
    int[][] arr3 = new int[3][2];
    arr3[0][1] = 78;
    System.out.println(arr3[0]);// [I@78308db1
    System.out.println(arr3[0][1]);// 78

    // 2-2 動態初始化,方式二
    /*
    二維陣列 arr4 中有 3 個一維陣列,內層每個一維陣列都是預設初始化值 null(注意:區別于格式 2-1)
    可以對內層三個一維陣列分別進行初始化
     */
    int[][] arr4 = new int[3][];
    // 初始化第一個
    arr4[0] = new int[3];
    // 初始化第二個
    arr4[1] = new int[1];
    // 初始化第三個
    arr4[2] = new int[2];
    
    // 3 特殊寫法
    int[] x, y[];// x 是一維陣列,y 是二維陣列
    x = new int[3];
    y = new int[3][2];
    
    // 4 獲取陣列長度
    System.out.println("arr的長度:" + arr.length);// 3
    System.out.println("arr第一個元素的長度:" + arr[0].length);// 3

    // 5 遍歷二維陣列
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            System.out.print(arr[i][j] + "\t");// 3	8 2	2 7	9 0	1 6
        }
    }
    System.out.println();

    // 6 簡寫遍歷二維陣列
    for (int[] valueArr : arr) {
        for (int value : valueArr) {
            System.out.print(value + "\t");// 3	8 2	2 7	9 0	1 6
        }
    }
    System.out.println();
    
    // 7 二維陣列元素的預設初始化值
    int[][] arr5 = new int[3][2];
    System.out.println(arr5);// [[I@27c170f0
    System.out.println(arr5[1]);// [I@5451c3a8
    System.out.println(arr5[1][1]);// 0

    String[][] arr6 = new String[3][2];
    System.out.println(arr6);// [[Ljava.lang.String;@2626b418
    System.out.println(arr6[1]);// [Ljava.lang.String;@5a07e868
    System.out.println(arr6[1][1]);// null

    String[][] arr7 = new String[3][];
    System.out.println(arr7[1]);// null,因為內層陣列未初始化
    System.out.println(arr7[1][1]);// NullPointerException
}
  • 動態初始化方式一,初始化時直接規定了內層一維陣列的長度,動態初始化方式二,可以在使用過程中根據需要另行初始化內層一維陣列的長度。利用動態初始化方式二時,必須要先初始化內層一維陣列才能對其使用,否則報空指標異常。
  • int[][] arr = new int[][3];的方式是非法的。
  • 注意特殊寫法情況:int[] x,y[];// x是一維陣列,y是二維陣列
  • Java 中多維陣列不必都是規則矩陣形式。
  • 陣列元素的預設初始化值:針對形如int[][] arr = new int[4][3];的初始化方式,外層元素的初始化值為地址值,內層元素的初始化值與一維陣列初始化情況相同;針對形如int[][] arr = new int[4][];的初始化方式,外層元素的初始化值為 null,內層元素沒有初始化,不能呼叫。

陣列應用

楊輝三角

楊輝三角:

image-20210219101905712

提示:

  1. 第一行有 1 個元素,第 n 行有 n 個元素。
  2. 每一行的第一個元素和最後一個元素都是 1。
  3. 從第三行開始,對於非第一個元素和最後一個元素的元素,有:yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];

實現:

public static void main(String[] args) {
    // 1 宣告二維陣列並初始化
    int[][] arrs = new int[10][];
    for (int i = 0; i < arrs.length; i++) {
        System.out.print("[" + i + "]\t");
        // 2 初始化內層陣列,並給內層陣列的首末元素賦值
        arrs[i] = new int[i + 1];
        arrs[i][0] = 1;
        arrs[i][arrs[i].length - 1] = 1;
        for (int j = 0; j < arrs[i].length; j++) {
            // 3 給從第三行開始內層陣列的非首末元素賦值
            if (i >= 2 && j > 0 && j < arrs[i].length - 1) {
                arrs[i][j] = arrs[i - 1][j - 1] + arrs[i - 1][j];
            }
            System.out.print(arrs[i][j] + "\t");
        }
        System.out.println();
    }
    System.out.print("\t");
    for (int i = 0; i < arrs.length; i++) {
        System.out.print("[" + i + "]\t");
    }
}

回形數

回形數,從鍵盤輸入一個 1 - 20 的整數,然後以該數字為矩陣的大小,把 1,2,3 … n*n 的數字按照順時針螺旋的形式填入其中。例如:

  • 輸入數字 2,則程式輸出:

    image-20210219104822490

  • 輸入數字 3,則程式輸出:

    image-20210219104929770

  • 輸入數字 4, 則程式輸出:

    image-20210219105019369

實現方式一:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("輸入一個數字");
    int len = scanner.nextInt();
    int[][] arr = new int[len][len];
    int s = len * len;

    /*
     * k = 1:向右,k = 2:向下,k = 3:向左,k = 4:向上
     */
    int k = 1;
    int i = 0, j = 0;
    for (int m = 1; m <= s; m++) {
        if (k == 1) {
            if (j < len && arr[i][j] == 0) {
                arr[i][j++] = m;
            } else {
                k = 2;
                i++;
                j--;
                m--;
            }
        } else if (k == 2) {
            if (i < len && arr[i][j] == 0) {
                arr[i++][j] = m;
            } else {
                k = 3;
                i--;
                j--;
                m--;
            }
        } else if (k == 3) {
            if (j >= 0 && arr[i][j] == 0) {
                arr[i][j--] = m;
            } else {
                k = 4;
                i--;
                j++;
                m--;
            }
        } else if (k == 4) {
            if (i >= 0 && arr[i][j] == 0) {
                arr[i--][j] = m;
            } else {
                k = 1;
                i++;
                j++;
                m--;
            }
        }
    }

    // 遍歷陣列
    for (int m = 0; m < arr.length; m++) {
        for (int n = 0; n < arr[m].length; n++) {
            System.out.print(arr[m][n] + "\t");
        }
        System.out.println();
    }
}

實現方式二:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("輸入一個數字");
    int n = scanner.nextInt();
    int[][] arr = new int[n][n];

    int count = 0;// 要顯示的資料
    int maxX = n - 1;// X 軸的最大下標
    int maxY = n - 1;// Y 軸的最大下標
    int minX = 0;// X 軸的最小下標
    int minY = 0;// Y 軸的最小下標
    while (minX <= maxX) {
        // 向右
        for (int x = minX; x <= maxX; x++) {
            arr[minY][x] = ++count;
        }
        minY++;
        // 向下
        for (int y = minY; y <= maxY; y++) {
            arr[y][maxX] = ++count;
        }
        maxX--;
        // 向左
        for (int x = maxX; x >= minX; x--) {
            arr[maxY][x] = ++count;
        }
        maxY--;
        // 向上
        for (int y = maxY; y >= minY; y--) {
            arr[y][minX] = ++count;
        }
        minX++;
    }

    // 遍歷陣列
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length; j++) {
            String space = (arr[i][j] + "").length() == 1 ? "0" : "";
            System.out.print(space + arr[i][j] + " ");
        }
        System.out.println();
    }
}

元素統計

定義一個 int 型的一維陣列,包含 10 個元素,分別賦一些隨機整數,然後求出所有元素的最大值,最小值,和值,平均值,並輸出出來。要求:所有隨機數都是兩位數。

public static void main(String[] args) {
    // 初始化及賦值
    int[] arr = new int[10];
    int length = arr.length;
    for (int i = 0; i < length; i++) {
        int value = (int) (Math.random() * 90 + 10);
        arr[i] = value;
    }

    // 遍歷
    for (int value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 計算
    int max = arr[0];
    int min = arr[0];
    int sum = 0;
    double average = 0;
    for (int value : arr) {
        max = max < value ? value : max;
        min = min > value ? value : min;
        sum += value;
    }
    average = sum / (length * 1.0);
    System.out.println("最大值:" + max);
    System.out.println("最小值:" + min);
    System.out.println("和值:" + sum);
    System.out.println("平均值:" + average);
}

陣列的複製

虛假的複製,沒有建立新物件:

public static void main(String[] args) {
    // 宣告 arr1 和 arr2
    int[] arr1, arr2;
    arr1 = new int[]{2, 3, 5, 7, 11, 13, 17, 19};

    // 遍歷 arr1
    for (int value : arr1) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 賦值 arr2 變數等於 arr1
    // 不能稱作陣列的複製,實際上是把 arr1 指向的地址(以及其他一些資訊)賦給了 arr2,堆空間中只有一個陣列物件
    arr2 = arr1;

    // 遍歷 arr2
    for (int value : arr2) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 更改 arr2
    for (int i = 0; i < arr1.length; i++) {
        if (i % 2 == 0) {
            arr2[i] = i;
            continue;
        }
        arr2[i] = arr1[i];
    }

    // 遍歷 arr2
    for (int value : arr2) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 遍歷 arr1
    for (int value : arr1) {
        System.out.print(value + "\t");
    }
    System.out.println();
}
輸出結果:
2	3	5	7	11	13	17	19	
2	3	5	7	11	13	17	19	
0	3	2	7	4	13	6	19	
0	3	2	7	4	13	6	19

真實的複製,建立了新物件:

public static void main(String[] args) {
    // 宣告 arr1 和 arr2
    int[] arr1, arr2;
    arr1 = new int[]{2, 3, 5, 7, 11, 13, 17, 19};

    // 遍歷 arr1
    for (int value : arr1) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 陣列的複製
    arr2 = new int[arr1.length];
    for (int i = 0; i < arr1.length; i++) {
        arr2[i] = arr1[i];
    }

    // 遍歷 arr2
    for (int value : arr2) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 更改 arr2
    for (int i = 0; i < arr1.length; i++) {
        if (i % 2 == 0) {
            arr2[i] = i;
            continue;
        }
        arr2[i] = arr1[i];
    }

    // 遍歷 arr2
    for (int value : arr2) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 遍歷 arr1
    for (int value : arr1) {
        System.out.print(value + "\t");
    }
    System.out.println();
}
輸出結果:
2	3	5	7	11	13	17	19	
2	3	5	7	11	13	17	19	
0	3	2	7	4	13	6	19	
2	3	5	7	11	13	17	19

陣列反轉

public static void main(String[] args) {
    String[] arr = {"A", "B", "C", "D", "E", "F", "G"};

    // 遍歷arr
    for (String value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 反轉,方式一
    for (int i = 0; i < arr.length / 2; i++) {
        String temp = arr[i];
        arr[i] = arr[arr.length - 1 - i];
        arr[arr.length - 1 - i] = temp;
    }
    for (String value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 反轉,方式二
    for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
        String temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    for (String value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();
}

陣列查詢

線性查詢
public static void main(String[] args) {
    String[] arr = {"A", "B", "C", "D", "E", "F", "G"};

    // 遍歷 arr
    for (String value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();
    
    String dest = "D";
    boolean isFlag = true;
    for (int i = 0; i < arr.length; i++) {
        if (dest.equals(arr[i])) {
            System.out.println("找到了指定的元素:" + dest + ",位置為:" + i);
            isFlag = false;
            break;
        }
    }
    if (isFlag) {
        System.out.println("沒找到指定的元素:" + dest);
    }
}
輸出結果:
A	B	C	D	E	F	G	
找到了指定的元素:D,位置為:3
二分法查詢

前提:所要查詢的陣列必須有序。

image-20210219153157857

public static void main(String[] args) {
    int[] arr = {2, 5, 7, 8, 10, 15, 18, 20, 22, 25, 28};
    
    // 遍歷 arr
    for (int value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();

    int dest = 10;
    // 初始的首索引
    int head = 0;
    // 初始的末索引
    int end = arr.length - 1;
    boolean isFlag = true;
    while (head <= end) {
        int middle = (head + end) / 2;
        if (dest == arr[middle]) {
            System.out.println("找到了指定的元素:" + dest + ",位置為:" + middle);
            isFlag = false;
            break;
        } else if (dest < arr[middle]) {
            end = middle - 1;
        } else {// dest2 > arr2[middle]
            head = middle + 1;
        }
    }
    if (isFlag) {
        System.out.println("沒找到指定的元素:" + dest);
    }
}
輸出結果:
2 5	7 8	10 15 18 20	22 25 28	
找到了指定的元素:10,位置為:4

陣列排序

排序:假設含有 n 個記錄的序列為 {R1, R2, ..., Rn},其相應的關鍵字序列為 {K1, K2, ..., Kn}。將這些記錄重新排序為 {Ri1, Ri2, ..., Rin},使得相應的關鍵字值滿足條 Ki1 <= Ki2 <= ... <= Kin,這樣的一種操作稱為排序。通常來說,排序的目的是快速查詢。

衡量排序演算法的優劣:

  1. 時間複雜度:分析關鍵字的比較次數和記錄的移動次數。

  2. 空間複雜度:分析排序演算法中需要多少輔助記憶體。

  3. 穩定性:若兩個記錄 A 和 B 的關鍵字值相等,但排序後 A、B 的先後次序保持不變,則稱這種排序演算法是穩定的。

排序演算法分類:內部排序和外部排序。

  • 內部排序:整個排序過程不需要藉助於外部儲存器(如磁碟等),所有排序操作都在記憶體中完成。

  • 外部排序:參與排序的資料非常多,資料量非常大,計算機無法把整個排序過程放在記憶體中完成,必須藉助於外部儲存器(如磁碟等)。外部排序最常見的是多路歸併排序。可以認為外部排序是由多次內部排序組成。

十大內部排序演算法:

  • 選擇排序
    • 直接選擇排序、堆排序
  • 交換排序
    • 氣泡排序、快速排序
  • 插入排序
    • 直接插入排序、折半插入排序、Shell 排序
  • 歸併排序
  • 桶式排序
  • 基數排序

排序演算法效能對比:

image-20210219203707336

  • 從平均時間而言:快速排序最佳。但在最壞情況下時間效能不如堆排序和歸併排序。
  • 從演算法簡單性看:由於直接選擇排序、直接插入排序和氣泡排序的演算法比較簡單,將其認為是簡單演算法。對於 Shell 排序、堆排序、快速排序和歸併排序演算法,其演算法比較複雜,認為是複雜排序。
  • 從穩定性看:直接插入排序、氣泡排序和歸併排序時穩定的;而直接選擇排序、快速排序、 Shell 排序和堆排序是不穩定排序。
  • 從待排序的記錄數 n 的大小看,n 較小時,宜採用簡單排序;而 n 較大時宜採用改進排序。

排序演算法的選擇:

  • 若 n 較小(如 n ≤50),可採用直接插入或直接選擇排序。當記錄規模較小時,直接插入排序較好;否則因為直接選擇移動的記錄數少於直接插入,應選直接選擇排序為宜。
  • 若檔案初始狀態基本有序(指正序),則應選用直接插入、 冒泡或隨機的快速排序為宜。
  • 若 n 較大,則應採用時間複雜度為 O(nlgn) 的排序方法: 快速排序、 堆排序或歸併排序。
氣泡排序

氣泡排序的原理非常簡單,它重複地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。

排序思想:

  1. 比較相鄰的元素。如果第一個比第二個大(升序),就交換他們兩個。
  2. 對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。這步做完後,最後的元素會是最大的數。
  3. 針對所有的元素重複以上的步驟,除了最後一個。
  4. 持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較為止。

實現:

public static void main(String[] args) {
    int[] arr = new int[]{43, 32, 76, -98, 0, 64, 33, -21, 32, 99};

    // 遍歷 arr
    for (int value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();

    // 氣泡排序
    for (int i = 0; i < arr.length - 1; i++) {
        // 先把最大的數移到陣列最後一位,然後再找第二大的數,以此類推
        for (int j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // 遍歷 arr
    for (int value : arr) {
        System.out.print(value + "\t");
    }
    System.out.println();
}
輸出結果:
43	32	76	-98	0	64	33	-21	32	99
-98	-21	0	32	32	33	43	64	76	99
快速排序

快速排序通常明顯比同為 O(nlogn) 的其他演算法更快,因此常被採用,而且快速排序採用了分治法的思想,所以在很多筆試面試中能經常看到快速排序的影子,可見掌握快速排序的重要性。

快速排序(Quick Sort)由圖靈獎獲得者 Tony Hoare 發明,被列為 20 世紀十大演算法之一,是迄今為止所有內排序演算法中速度最快的一種。

快速排序屬於氣泡排序的升級版,交換排序的一種。快速排序的時間複雜度為 O(nlog(n))。

排序思想:

  1. 從數列中挑出一個元素,稱為 "基準"(pivot)。
  2. 重新排序數列,所有元素比基準值小的擺放在基準前面,所有元素比基準值大的擺在基準的後面(相同的數可以到任一邊)。在這個分割槽結束之後,該基準就處於數列的中間位置。這個稱為分割槽(partition)操作。
  3. 遞迴地(recursive)把小於基準值元素的子數列和大於基準值元素的子數列排序。
  4. 遞迴的最底部情形,是數列的大小是零或一,也就是永遠都已經被排序好了。雖然一直遞迴下去,但是這個演算法總會結束,因為在每次的迭代(iteration)中,它至少會把一個元素擺到它最後的位置去。

image-20210219173315424

image-20210219173351751

Arrays 工具類的使用

java.util.Arrays類為運算元組的工具類,包含了用來運算元組(比如排序和搜尋)的各種方法。常用的方法有:

  • boolean equals(int[] a, int[] b):判斷兩個陣列是否相等。
  • String toString(int[] a):遍歷陣列資訊。
  • void fill(int[] a, int val):將指定值填充到陣列之中。
  • void sort(int[] a):對陣列進行排序,底層使用的是快速排序。
  • int binarySearch(int[] a, int key):對排序後的陣列進行二分法檢索指定的值。

示例:

public static void main(String[] args) {
    // 1 boolean equals(int[] a, int[] b):判斷兩個陣列是否相等
    int[] arr1 = new int[]{1, 2, 3, 4};
    int[] arr2 = new int[]{1, 3, 2, 4};
    boolean isEquals = Arrays.equals(arr1, arr2);
    System.out.println("arr1和arr2是否相等:" + isEquals);

    // 2 String toString(int[] a):遍歷陣列資訊
    System.out.println("arr1:" + Arrays.toString(arr1));

    // 3 void fill(int[] a, int val):將指定值填充到陣列之中
    Arrays.fill(arr1, 10);
    System.out.println("arr1填充後:" + Arrays.toString(arr1));

    // 4 void sort(int[] a):對陣列進行排序,底層使用的是快速排序
    System.out.println("arr2排序前:" + Arrays.toString(arr2));
    Arrays.sort(arr2);
    System.out.println("arr2排序後:" + Arrays.toString(arr2));

    // 5 int binarySearch(int[] a, int key):對排序後的陣列進行二分法檢索指定的值
    int[] arr3 = new int[]{-98, -34, 2, 34, 54, 66, 79, 105, 210, 333};
    int dest = 211;
    int index = Arrays.binarySearch(arr3, dest);
    if (index >= 0) {
        System.out.println(dest + "在陣列中的位置為:" + index);
    } else {
        System.out.println(dest + "在陣列中未找到:" + index);
    }
}
輸出結果:
arr1和arr2是否相等:false
arr1:[1, 2, 3, 4]
arr1填充後:[10, 10, 10, 10]
arr2排序前:[1, 3, 2, 4]
arr2排序後:[1, 2, 3, 4]
211在陣列中未找到:-10

陣列中的異常

public static void main(String[] args) {
    // ArrayIndexOutOfBoundsException
    int[] arr = new int[]{7, 10};
    System.out.println(arr[2]);// 陣列腳標越界
    System.out.println(arr[-1]);// 訪問了陣列中不存在的腳標

    // NullPointerException:空指標異常,arr 引用沒有指向實體,卻被操作實體中的元素
    // 情形一
    int[] arr2 = null;
    System.out.println(arr2[0]);
    // 情形二
    int[][] arr3 = new int[4][];
    System.out.println(arr3[0]);// null
    System.out.println(arr3[0][0]);// NullPointerException
    // 情形三
    String[] arr4 = new String[]{"AA", "BB", "CC"};
    arr4[0] = null;
    System.out.println(arr4[0].toString());// 對 null 呼叫了方法
}

ArrayIndexOutOfBoundsException 和 NullPointerException,在編譯時,不報錯!!

List 介面

List 集合類中元素有序、且可重複,集合中的每個元素都有其對應的順序索引。

ArrayList

基礎屬性:

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    @java.io.Serial
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
}

本文原始碼,均基於 JDK 17。

new ArrayList() 時,底層 Object[] 陣列 elementData 初始化為 {},是一個長度為 0 的空陣列

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

第一次呼叫 add() 方法,初始化底層 Object[] 陣列 elementData 的長度為 10,並將元素新增到 elementData 中:

/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return {@code true} (as specified by {@link Collection#add})
 */
public boolean add(E e) {
    modCount++;
    add(e, elementData, size);
    return true;
}
/**
 * This helper method split out from add(E) to keep method
 * bytecode size under 35 (the -XX:MaxInlineSize default value),
 * which helps when add(E) is called in a C1-compiled loop.
 */
private void add(E e, Object[] elementData, int s) {
    // 第一次執行 add() 方法,size 屬性的值為 0,elementData.length 為 0
    if (s == elementData.length)
        elementData = grow();
    // 新增元素到陣列中
    elementData[s] = e;
    size = s + 1;
}
private Object[] grow() {
    return grow(size + 1);
}
/**
 * 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) {
    int oldCapacity = elementData.length;
    if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        int newCapacity = ArraysSupport.newLength(oldCapacity,
                minCapacity - oldCapacity, /* minimum growth */
                oldCapacity >> 1           /* preferred growth */);
        return elementData = Arrays.copyOf(elementData, newCapacity);
    } else {
        // 初始化陣列,長度為 DEFAULT_CAPACITY,即 10
        return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
    }
}

之後,每次執行 add() 方法,直接將元素新增到 elementData 對應的位置,直到第 11 次新增元素。此時,新增的元素的總數,已經超過了陣列的長度,需要進行擴容操作

/**
 * This helper method split out from add(E) to keep method
 * bytecode size under 35 (the -XX:MaxInlineSize default value),
 * which helps when add(E) is called in a C1-compiled loop.
 */
private void add(E e, Object[] elementData, int s) {
    // 第 11 次新增元素,此時,滿足 s == elementData.length 條件
    if (s == elementData.length)
        elementData = grow();
    elementData[s] = e;
    size = s + 1;
}

預設情況下,陣列長度擴容為原來容量的 1.5 倍,同時,將原有陣列中的資料複製到新的陣列中

/**
 * 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) {
    int oldCapacity = elementData.length;
    // 滿足 oldCapacity > 0 條件
    if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        // 擴容陣列長度到原來的 1.5 倍
        int newCapacity = ArraysSupport.newLength(oldCapacity,
                minCapacity - oldCapacity, /* minimum growth */
                oldCapacity >> 1           /* preferred growth */);
        // 複製原陣列資料到新陣列
        return elementData = Arrays.copyOf(elementData, newCapacity);
    } else {
        return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
    }
}

結論:

  1. ArrayList 是第一次新增元素時,才建立一個初始容量為 10 的陣列,延遲了陣列的建立。
  2. 新增資料時,如果底層的陣列需要擴容,均擴容為原來容量的 1.5 倍,同時,將原有陣列中的資料複製到新的陣列中。
  3. 開發中使用 ArrayList 時,建議按需求在初始化時就指定 ArrayList 的容量,以儘可能的避免擴容。

LinkedList

雙向連結串列,內部定義了內部類 Node,作為 LinkedList 中儲存資料的基本結構。

LinkedList 內部沒有宣告陣列,而是定義了 Node 型別的 first 和 last,用於記錄首末元素:

image-20210322150052189

對於頻繁的插入或刪除元素的操作,建議使用 LinkedList 類,效率較高。

new LinkedList() 時,內部宣告瞭 Node 型別的 first 和 last 屬性,預設值為 null:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    transient int size = 0;

    /**
     * Pointer to first node.
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     */
    transient Node<E> last;

    /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }
}
// Node 內部類
private static class Node<E> {
    // 當前 Node 儲存的資料
    E item;
    // 指向連結串列的後一個元素
    Node<E> next;
    // 指向連結串列的前一個元素
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

呼叫 add() 方法新增元素:

/**
 * Appends the specified element to the end of this list.
 *
 * <p>This method is equivalent to {@link #addLast}.
 *
 * @param e element to be appended to this list
 * @return {@code true} (as specified by {@link Collection#add})
 */
public boolean add(E e) {
    linkLast(e);
    return true;
}
/**
 * Links e as last element.
 */
void linkLast(E e) {
    // last,原連結串列的最後一個物件
    final Node<E> l = last;
    // 建立一個新的 Node 物件
    final Node<E> newNode = new Node<>(l, e, null);
    // 當前新建立的 Node 物件,成為新連結串列的最後一個物件
    last = newNode;
    if (l == null)
        // 如果原連結串列為 null,則將當前新建立的 Node 物件指定為連結串列的第一個節點 first
        first = newNode;
    else
        // 如果原連結串列不為 null,則將原連結串列的最後一個物件,指向當前新的 Node 物件
        l.next = newNode;
    size++;
    modCount++;
}

Set 介面

Set 集合儲存無序的、不可重複的資料,如果把兩個相同的元素加入同一個 Set 集合中,則新增操作失敗。

  • 無序性:不等於隨機性。以 HashSet 為例,儲存的資料在底層陣列中並非按照陣列索引的順序新增,而是根據資料的雜湊值決定的。
  • 不可重複性:保證新增的元素按照 equals() 判斷時,不能返回 true。即:相同的元素只能新增一個。

Set 介面是 Collection 的子介面,Set 介面沒有提供額外的方法,使用的都是Collection中宣告過的方法。

Set 判斷兩個物件是否相同不是使用 == 運算子,而是根據 equals()。對於存放在 Set(主要指:HashSet、LinkedHashSet)容器中的物件,其對應的類一定要重寫equals()hashCode(),以實現物件相等規則。

  • 要求:重寫的 hashCode() 和 equals() 儘可能保持一致性,即:相等的物件必須具有相等的雜湊碼
    • 如果不重寫所新增元素所在類的 hashCode(),則會呼叫 Object 類的 hashCode(),該方法是產生一個隨機數,因此,即使新增兩個一樣的元素,其 hashCode 值也可能不同,也就都能新增成功。
  • 重寫兩個方法的小技巧:物件中用作 equals() 方法比較的 Field,都應該用來計算 hashCode 值。
  • TreeSet 比較兩個元素是否相同的方法,不是 equals() 和 hashCode(),而是元素對應類的排序方法。

重寫 hashCode() 方法的基本原則:

  • 在程式執行時,同一個物件多次呼叫 hashCode() 方法應該返回相同的值。
  • 當兩個物件的 equals() 方法比較返回 true 時,這兩個物件的 hashCode() 方法的返回值也應相等。
  • 物件中用作 equals() 方法比較的 Field,都應該用來計算 hashCode 值。

重寫 equals() 方法的基本原則,以自定義的 Customer 類為例,何時需要重寫 equals():

  • 如果一個類有自己特有的 "邏輯相等" 概念,當重寫 equals() 的時候,總是需要重寫 hashCode()。因為根據一個類改寫後的 equals(),兩個截然不同的例項有可能在邏輯上是相等的,但是,根據 Object 類的 hashCode(),它們僅僅是兩個物件。這種情況,違反了 "相等的物件必須具有相等的雜湊碼" 的原則。

結論:重寫 equals() 的時候,一般都需要同時重寫 hashCode() 方法。通常參與計算 hashCode 的物件的屬性也應該參與到 equals() 中進行計算。

Eclipse/IDEA 工具裡 hashCode() 的重寫,為什麼會有 31 這個數字:

@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
  • 選擇係數的時候要選擇儘量大的係數,因為如果計算出來的 hashCode 值越大,所謂的衝突就越少,查詢起來效率也會提高。---> 減少衝突
  • 31 只佔用 5 bits,相乘造成資料溢位的機率較小。
  • 31 可以由i * 31 == (i << 5) - 1來表示,現在很多虛擬機器裡面都有做相關最佳化。---> 提高演算法效率
  • 31 是一個素數,素數作用就是如果用一個數字來乘以這個素數,那麼最終出來的結果只能被素數本身和被乘數還有 1 來整除!---> 減少衝突

HashSet

HashSet 按 Hash 演算法來儲存集合中的元素,因此具有很好的存取、查詢、刪除效能。

HashSet 具有以下特點:

  • 不保證元素的排列順序。
  • 不是執行緒安全的。
  • 集合元素可以是 null,但是隻能有一個。

HashSet 的底層,使用的是 HashMap:

/**
 * Constructs a new, empty set; the backing {@code HashMap} instance has
 * default initial capacity (16) and load factor (0.75).
 */
public HashSet() {
    map = new HashMap<>();
}

LinkedHashSet

LinkedHashSet 根據元素的 hashCode 值來決定元素的儲存位置,但它同時使用雙向連結串列維護元素的次序,這使得元素看起來是以插入順序儲存的。

  • 遍歷 LinkedHashSet 內部資料時,可以按照新增的順序遍歷。

LinkedHashSet 插入效能略低於 HashSet,但在迭代訪問 Set 裡的全部元素時有很好的效能。對於頻繁的遍歷操作,LinkedHashSet 效率高於 HashSet。

LinkedHashSet 的底層,使用的是 LinkedHashMap:

public LinkedHashSet() {
    super(16, .75f, true);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

Map 介面

HashMap

HashMap 原始碼中的重要常量:

  • DEFAULT_INITIAL_CAPACITY:HashMap 的預設容量,16

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    
  • MAXIMUM_CAPACITY:HashMap 的最大支援容量,$2^{30}$。

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
  • DEFAULT_LOAD_FACTOR:HashMap 的預設載入因子,0.75

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    • 不同於 ArrayList,HashMap 不是在底層陣列全部填滿時才進行擴容操作,因為陣列上有一些位置可能會一直都沒有新增元素,但其他位置上元素可能有很多,導致連結串列和二叉樹結構變多。因此,會在元素新增到一定數量時,就執行擴容操作,即新增元素數量達到 threshold 值時擴容。預設載入因子如果過小,會導致陣列還有很多空位置時擴容,陣列利用率低;預設載入因子如果過大,會導致陣列中存在很多元素時才擴容,連結串列和二叉樹結構過多。因此,預設載入因子在 0.7 ~ 0.75 左右比較合適。
  • TREEIFY_THRESHOLD:Bucket 中連結串列儲存的 Node 長度大於該預設值,判斷是否轉換為紅黑樹,預設為 8

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;
    
  • UNTREEIFY_THRESHOLD:Bucket 中紅黑樹儲存的 Node 長度小於該預設值,轉換為連結串列,預設為 6

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;
    
  • MIN_TREEIFY_CAPACITY:桶中的 Node 被樹化時最小的 hash 表容量,預設為 64。

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
    
    • 當桶中 Node 的數量大到需要變紅黑樹(8)時,若 hash 表容量小於 MIN_TREEIFY_CAPACITY,此時應執行 resize() 進行擴容操作。MIN_TREEIFY_CAPACITY 的值至少是 TREEIFY_THRESHOLD 的 4 倍。
  • table儲存元素的陣列,長度總是 2 的 n 次冪。

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;
    
  • entrySet:儲存具體元素的集。

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;
    
  • size:HashMap 中已儲存的鍵值對的數量。

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;
    
  • modCount:HashMap 擴容和結構改變的次數。

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;
    
  • threshold:擴容的臨界值,其值一般等於(容量 * 載入因子),(int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);。擴容的操作不是當底層陣列全部被填滿後再擴容,而是達到臨界值後的下一次新增操作進行擴容。

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;
    
  • loadFactor:載入因子。

    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;
    

new HashMap<>() 時,賦值載入因子 loadFactor 為 DEFAULT_LOAD_FACTOR,即 0.75

/**
 * Constructs an empty {@code HashMap} with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

第一次呼叫 put() 方法時,透過 resize() 方法,建立一個長度為 16 的 Node 陣列

/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 * @return the previous value associated with {@code key}, or
 *         {@code null} if there was no mapping for {@code key}.
 *         (A {@code null} return can also indicate that the map
 *         previously associated {@code null} with {@code key}.)
 */
public V put(K key, V value) {
    // key 做 hash
    return putVal(hash(key), key, value, false, true);
}
/**
 * Implements Map.put and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        // 第一次呼叫 put() 方法,此時,table 未初始化,為 null,呼叫 resize() 方法,建立長度為 16 的 Node 陣列
        n = (tab = resize()).length;
    // 然後,檢視 Node 陣列中的位置 i 的元素 p,是否為 null
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 如果 p 為 null,說明當前位置 i 沒有元素,新增成功 ---> 情況 1
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            // 位置 i 上的元素,與當前待新增元素的 key 相同
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 位置 i 上的元素,與當前待新增元素的 key 不同
            for (int binCount = 0; ; ++binCount) {
                // 位置 i 上,只有一個元素
                if ((e = p.next) == null) {
                    // 位置 i 上的原元素指向當前待新增的元素,新增成功 ---> 情況 2 和 3
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        // 如果連結串列的長度超過 8 時,判斷是否轉為紅黑樹結構
                        treeifyBin(tab, hash);
                    break;
                }
                // 位置 i 上,不止一個元素,依次獲得該連結串列上的每一個元素,與當前待新增元素的 key,對比 hash 值和 equals() 方法
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        // 預設陣列長度 16
        newCap = DEFAULT_INITIAL_CAPACITY;
        // 預設擴容的臨界值 0.75 * 16 = 12
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    // 賦值擴容的臨界值 12
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    // 建立一個長度為 16 的 Node 陣列
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

計算 key 的 hash 值:

/**
 * Computes key.hashCode() and spreads (XORs) higher bits of hash
 * to lower.  Because the table uses power-of-two masking, sets of
 * hashes that vary only in bits above the current mask will
 * always collide. (Among known examples are sets of Float keys
 * holding consecutive whole numbers in small tables.)  So we
 * apply a transform that spreads the impact of higher bits
 * downward. There is a tradeoff between speed, utility, and
 * quality of bit-spreading. Because many common sets of hashes
 * are already reasonably distributed (so don't benefit from
 * spreading), and because we use trees to handle large sets of
 * collisions in bins, we just XOR some shifted bits in the
 * cheapest possible way to reduce systematic lossage, as well as
 * to incorporate impact of the highest bits that would otherwise
 * never be used in index calculations because of table bounds.
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

判斷連結串列是否轉紅黑樹:

/**
 * Replaces all linked nodes in bin at index for given hash unless
 * table is too small, in which case resizes instead.
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        // 如果底層陣列的長度小於 64,只擴容,不轉紅黑樹
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

總結:

  • new HashMap<>() 時,底層沒有建立陣列,只賦值載入因子 loadFactor 為 0.75。
  • 首次呼叫 put() 方法時,底層建立長度為 16 的 Node 陣列。
  • 執行 map.put(key1, value1) 操作,可能已經執行過多次 put() 方法:
    • 首先,計算 key1 所在類的 hashCode() 以及其他操作計算 key1 的雜湊值,此雜湊值經過某種演算法計算以後,得到在 Node 陣列中的存放位置。

    • 如果此位置上的資料為空,此時的 key1 - value1 新增成功。---> 情況 1

    • 如果此位置上的資料不為空,意味著此位置上存在一個或多個資料,比較 key1 和已經存在的一個或多個資料的雜湊值:

      • 如果 key1 的雜湊值與已經存在的資料的雜湊值都不相同,此時 key1 - value1 新增成功。---> 情況 2
      • 如果 key1 的雜湊值和已經存在的某一個資料(key2 - value2)的雜湊值相同,則呼叫 key1 所在類的 equals(key2),繼續比較:
        • 如果 equals() 返回 false:此時 key1 - value1 新增成功。---> 情況 3
        • 如果 equals() 返回 true:使用 value1 替換 value2。
    • 補充:關於情況 2 和情況 3,此時 key1 - value1 和原來的資料以連結串列的方式儲存。

  • 當陣列的某一個索引位置上的元素以連結串列形式存在的資料個數 > 8 且當前陣列的長度 > 64時,此時此索引位置上的資料改為使用紅黑樹儲存。

儲存結構:陣列 + 連結串列 + 紅黑樹

1722141753815

  • HashMap 的內部儲存結構其實是陣列 + 連結串列 + 紅黑樹的結合。當例項化一個 HashMap 時,會初始化 initialCapacity 和 loadFactor,在 put 第一對對映關係時,系統會建立一個長度為 initialCapacity 的 Node 陣列,這個長度在雜湊表中被稱為容量(Capacity),在這個陣列中可以存放元素的位置我們稱之為 "桶"(Bucket),每個 Bucket 都有自己的索引,系統可以根據索引快速的查詢 Bucket 中的元素。
  • 每個 Bucket 中儲存一個元素,即一個 Node 物件,但每一個 Node 物件可以帶一個引用變數 next,用於指向下一個元素,因此,在一個桶中,就有可能生成一個 Node 鏈。也可能是一個一個 TreeNode 物件,每一個 TreeNode 物件可以有兩個葉子結點 left 和 right,因此,在一個桶中,就有可能生成一個 TreeNode 樹。而新新增的元素作為連結串列的 last,或樹的葉子結點。

擴容過程:

  • 當 HashMap 中的元素越來越多的時候,hash 衝突的機率也就越來越高,因為底層陣列的長度是固定的。所以為了提高查詢的效率,就要對 HashMap 的底層陣列進行擴容,而在 HashMap 陣列擴容之後,最消耗效能的點就出現了:原陣列中的資料必須重新計算其在新陣列中的位置,並放進去,這就是resize()
  • 當 HashMap 中的元素個數超過 "陣列大小(陣列總大小 length,不是陣列中儲存的元素個數 size) * loadFactor" 時 , 就會進行陣列擴容 。其中,loadFactor 的 預設值為 0.75,這是一個折中的取值,預設情況下,陣列大小為 16,那麼當 HashMap 中元素個數 ≥ 16 * 0.75 = 12 (這個值就是程式碼中的 threshold 值,也叫做臨界值)且要存放的位置非空的時候,就把陣列的大小擴充套件為 2 * 16 = 32,即擴大一倍,然後重新計算每個元素在陣列中的位置,把原有的資料複製到新陣列中。
  • 擴容是一個非常消耗效能的操作,如果已經預知 HashMap 中元素的個數,那麼預設元素的個數能夠有效的提高 HashMap 的效能。

LinkedHashMap

LinkedHashMap 在 HashMap 儲存結構的基礎上,使用了一對雙向連結串列來記錄新增元素的順序,對於頻繁的遍歷操作,執行效率高於 HashMap。

  • LinkedHashMap 在遍歷元素時,可以按照新增的順序實現遍歷。

LinkedHashMap 在原有的 HashMap 底層結構基礎上,新增了一對指標 befor 和 after,指向當前元素的前一個和後一個元素:

/**
 * HashMap.Node subclass for normal LinkedHashMap entries.
 */
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}

擴充套件

紅黑樹在 HashMap 中的應用

HashMap 在 Java 8 中引入了紅黑樹作為連結串列的替代資料結構,用於在發生雜湊衝突時最佳化查詢效能,紅黑樹的引入主要是為了提高高衝突情況下的效能。

下面是詳細解釋:

  1. 連結串列的效能問題。在早期版本的 HashMap 中,當多個鍵的雜湊值相同時,這些鍵值對會儲存在同一個連結串列中。如果雜湊衝突較多,連結串列變長,查詢、插入和刪除操作的時間複雜度會從平均情況下的 O(1) 降到最壞情況下的 O(n),其中 n 是連結串列的長度。

  2. 紅黑樹的引入。紅黑樹是一種自平衡二叉搜尋樹,具有以下特性:

  • 每個節點都是紅色或黑色。
  • 根節點是黑色。
  • 所有葉子節點(NIL 節點)都是黑色。
  • 如果一個節點是紅色,則其兩個子節點都是黑色(即不能有兩個連續的紅色節點)。
  • 從任一節點到其每個葉子的所有路徑都包含相同數目的黑色節點。
  • 以上這些特性,使得紅黑樹在最壞情況下的時間複雜度為 O(log n),其中 n 是樹的節點數。這意味著,即使在發生大量雜湊衝突的情況下,查詢、插入和刪除操作的效能也能得到保證。
  1. 紅黑樹在 HashMap 中的應用。在 Java 8 及之後的版本中,HashMap 在發生雜湊衝突時,會根據連結串列的長度決定是否將連結串列轉換為紅黑樹:
  • 當連結串列長度超過某個閾值(預設是 8),HashMap 會將連結串列轉換為紅黑樹。
  • 當紅黑樹節點數量下降到某個閾值(預設是 6)以下時,紅黑樹會重新轉換為連結串列。
  • 這樣做的目的是在連結串列較短時保持簡單的連結串列結構(因為連結串列在長度較短時效能很好且佔用記憶體較小),而在連結串列較長時切換到紅黑樹以提高效能。
  1. 紅黑樹的實現。HashMap 中的紅黑樹由一個內部類 TreeNode 表示,TreeNode 類繼承了 HashMap 的 Node 類,並增加了紅黑樹特有的屬性和方法。以下是簡化的 TreeNode 類定義:
/**
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
  // 父節點
  TreeNode<K,V> parent;  // red-black tree links
  // 左子節點
  TreeNode<K,V> left;
  // 右子節點
  TreeNode<K,V> right;
  // 前一個節點
  TreeNode<K,V> prev;    // needed to unlink next upon deletion
  // 節點顏色
  boolean red;
  
  TreeNode(int hash, K key, V val, Node<K,V> next) {
      super(hash, key, val, next);
  }
  
  // 紅黑樹相關的方法,如插入、刪除、旋轉等
}

結論:HashMap 使用紅黑樹來處理高衝突情況下的效能問題,這樣可以保證在最壞情況下,查詢、插入和刪除操作的時間複雜度為 O(log n),從而提高了 HashMap 的整體效能和穩定性。這種設計使得 HashMap 在面對大量資料和高衝突時依然能夠保持高效的效能表現。

紅黑樹 vs B+Tree

紅黑樹和 B+Tree是兩種常用的資料結構,它們都有各自的應用場景和特點。下面詳細介紹這兩種資料結構的區別:

  1. 資料結構和節點型別
  • 紅黑樹
    • 是一種自平衡的二叉搜尋樹。
    • 每個節點包含一個鍵和值,以及顏色屬性(紅色或黑色)。
    • 每個節點最多有兩個子節點。
  • B+Tree:
    • 是一種多路搜尋樹,常用於資料庫和檔案系統中。
    • 每個節點可以有多個子節點和多個鍵。
    • 所有的鍵值對都儲存在葉子節點,內節點只儲存鍵不儲存值。
    • 葉子節點形成一個有序連結串列,便於範圍查詢。
  1. 平衡機制
  • 紅黑樹
    • 透過紅黑規則(如紅色節點不能有紅色子節點、從根到葉子的所有路徑包含相同數量的黑色節點等)來保持平衡。
    • 透過旋轉和重新著色操作進行自平衡,插入和刪除操作的時間複雜度為 O(log n)。
  • B+Tree
    • 透過分裂和合並操作來保持平衡。
    • 每個節點(除根節點外)至少有 ⌈m/2⌉ - 1 個鍵,最多有 m - 1 個鍵,其中 m 是樹的階數。
    • 內節點的插入和刪除操作可能會引發分裂和合並,但時間複雜度也是 O(log n)。
  1. 應用場景
  • 紅黑樹
    • 主要用於記憶體中的資料結構,例如 TreeMap 和 TreeSet。
    • 適合需要頻繁插入、刪除和查詢操作的場景。
  • B+Tree
    • 主要用於磁碟儲存的資料庫索引和檔案系統。
    • 適合需要高效範圍查詢和順序訪問的場景。
    • 由於葉子節點構成有序連結串列,範圍查詢效率較高。
  1. 查詢效能
  • 紅黑樹
    • 查詢單個元素的時間複雜度為 O(log n)。
    • 不適合大規模範圍查詢,因為需要遍歷樹結構。
  • B+Tree
    • 查詢單個元素的時間複雜度也是 O(log n)。
    • 範圍查詢效能優越,因為葉子節點形成有序連結串列,查詢可以在連結串列中順序遍歷。
  1. 儲存效率
  • 紅黑樹
    • 每個節點儲存一個鍵和值,以及指向左右子節點的指標和顏色資訊。
    • 節點的儲存開銷相對較小。
  • B+Tree
    • 內節點儲存多個鍵和指向子節點的指標,葉子節點儲存鍵值對。
    • 內節點的儲存開銷較大,但可以有效減少樹的高度,適合磁碟儲存。
  1. 葉子節點
  • 紅黑樹
    • 葉子節點可以包含資料,也可以為空(表示樹的末端)。
  • B+Tree
    • 所有資料都儲存在葉子節點,內節點只儲存索引。
    • 葉子節點透過指標相連,形成有序連結串列。
  1. 插入和刪除
  • 紅黑樹

    • 插入操作:

      • 新節點首先作為紅色節點插入。
      • 可能需要透過旋轉和重新著色來修復紅黑樹的平衡性質。
    • 刪除操作:

      • 如果刪除的節點是紅色節點,直接刪除即可。
      • 如果刪除的節點是黑色節點,可能需要透過旋轉和重新著色來修復紅黑樹的平衡性質。
  • B+Tree

    • 插入操作:

      • 插入新鍵時,如果目標節點已滿,需要進行節點分裂。
      • 新的鍵會被推到父節點,可能引發遞迴的節點分裂。
    • 刪除操作:

      • 刪除鍵時,如果節點中的鍵數量低於最低要求(通常是 ⌈m/2⌉ - 1 個鍵),需要進行節點合併或重新分配。
      • 這些操作可能引發遞迴的合併或重新分配,直到樹恢復平衡。

總結:

  • 紅黑樹
    • 適用於記憶體中的高效查詢、插入和刪除操作。
    • 不適合大規模的範圍查詢。
    • 結構相對簡單,節點儲存開銷較小。
  • B+Tree
    • 適用於資料庫和檔案系統中的索引結構,特別是磁碟儲存。
    • 適合大規模的範圍查詢和順序訪問。
    • 由於內節點儲存多個鍵和指向子節點的指標,儲存開銷較大,但樹的高度較小,適合減少磁碟 I/O。

原文連結

https://github.com/ACatSmiling/zero-to-zero/blob/main/JavaLanguage/java-advanced.md

相關文章