1、Arrays類概述
· 針對數組進行操作的工具類。
· 提供了排序,查找等功能。
2、成員方法
· public static String toString(int[] a):in[] a可以改為其他類型的數組,把數組轉成字符串
· public static void sort(int[] a):將各種類型的數組進行升序排序
· public static int binarySearch(int[] a,int key):將各種類型的數組進行二分查找
public class ArraysDemo01 { public static void main(String[] args) { // 定義一個數組 int[] arr = { 24, 69, 80, 57, 13 }; // public static String toString(int[] a) 把數組轉成字符串 System.out.println("排序前:"+ Arrays.toString(arr)); //排序前:[24, 69, 80, 57, 13] // public static void sort(int[] a) 對數組進行排序 Arrays.sort(arr); System.out.println("排序后:"+Arrays.toString(arr)); //排序后:[13, 24, 57, 69, 80] int[] arr2 = {13, 24, 57, 69, 80}; // public static int binarySearch(int[] a,int key) 二分查找 System.out.println("binarySearch:"+Arrays.binarySearch(arr2,57)); //binarySearch:2 System.out.println("binarySearch:"+Arrays.binarySearch(arr2,557)); //binarySearch:-6 return -(low+1) } }
3、Arrays類常用方法源碼詳細解釋
public static String toString(int[] a) public static void sort(int[] a) 底層是快速排序 public static int binarySearch(int[] a,int key) 開發原則: 只要是對象,我們就要判斷該對象是否為null。 測試代碼: int[] arr = { 24, 69, 80, 57, 13 }; System.out.println("排序前:" + Arrays.toString(arr)); sort源碼: public static String toString(int[] a) { //a -- arr -- { 24, 69, 80, 57, 13 } if (a == null) return "null"; //說明數組對象不存在 int iMax = a.length - 1; //iMax=4; if (iMax == -1) return "[]"; //說明數組存在,但是沒有元素。 StringBuilder b = new StringBuilder(); b.append('['); //"[" for (int i = 0; ; i++) { b.append(a[i]); //"[24, 69, 80, 57, 13" if (i == iMax) //"[24, 69, 80, 57, 13]" return b.append(']').toString(); b.append(", "); //"[24, 69, 80, 57, " } } ----------------------------------------------------- 測試代碼: int[] arr = {13, 24, 57, 69, 80}; System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577)); binarySearch源碼: public static int binarySearch(int[] a, int key) { //a -- arr -- {13, 24, 57, 69, 80} //key -- 577 return binarySearch0(a, 0, a.length, key); } private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { //a -- arr -- {13, 24, 57, 69, 80} //fromIndex -- 0 //toIndex -- 5 //key -- 577 int low = fromIndex; //low=0 int high = toIndex - 1; //high=4 while (low <= high) { int mid = (low + high) >>> 1; //mid=2,mid=3,mid=4 int midVal = a[mid]; //midVal=57,midVal=69,midVal=80 if (midVal < key) low = mid + 1; //low=3,low=4,low=5 else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }