Arrays工具類經常使用方法演示

java.util.Arrays是JDK中操做數組的工具類,包含了用來操做數組(好比排序和搜索)的各類方法。java

下面咱們以int類型數組爲例,學習下經常使用的方法,其餘類型數組都差很少。算法

1.equals(int[] a, int[] b)方法:判斷兩個數組是否相等

int[] array1 = new int[]{1, 2, 3, 4};
    int[] array2 = new int[]{1, 2, 3, 4};
    int[] array3 = new int[]{1, 3, 2, 4};
    boolean b1 = Arrays.equals(array1, array2);
    boolean b2 = Arrays.equals(array1, array3);
    System.out.println(b1);// 返回true
    System.out.println(b2);// 返回false
複製代碼

2.toString(int[] a)方法:返回一個指定數組的字符串表現形式

int[] array1 = new int[]{1, 2, 3, 4};
    System.out.println(Arrays.toString(array1));
	// 輸出結果爲[1, 2, 3, 4]
複製代碼

3.fill(int[] a, int value)方法:給指定數組的每一個元素分配指定的值

int[] array1 = new int[5];
    Arrays.fill(array1, 1);
    System.out.println(Arrays.toString(array1));
	// 輸出結果爲[1, 1, 1, 1, 1]
複製代碼

4.sort(int[] a):按升序對指定數組進行排序

int[] array = new int[]{99, 23, 33, 0, 65, 9, 16, 84};
    Arrays.sort(array);
    System.out.println(Arrays.toString(array));
	// 輸出結果爲[0, 9, 16, 23, 33, 65, 84, 99]
複製代碼

5.binarySearch(int[] a, int value):使用二分搜索算法在指定的數組中搜索指定的值,並返回該值所在索引位置;若查詢不到,則返回-1

int[] array = new int[]{1, 17, 20, 44, 45, 62, 79, 88, 93};
    int i = Arrays.binarySearch(array, 44);
    System.out.println(i);
	// 輸出結果爲3
複製代碼

相關文章
相關標籤/搜索