Arrays工具類常用方法演示


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

下面我們以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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM