Java基础知识强化63:Arrays工具类之方法源码解析

1. Arrays工具类的sort方法:

1 public static  void sort(int[]  a);

底层是快速排序,知道就可以了,用空看。

2. Arrays工具类的toString方法底层:

1 public static String toString(int[] a);

上面方法的底层是:

 1 public static String toString(int[] a) {
 2     //a -- arr -- { 24, 69, 80, 57, 13 }
 3 
 4     if (a == null)
 5         return "null"; //说明数组对象不存在
 6     int iMax = a.length - 1; //iMax=4;
 7     if (iMax == -1)
 8         return "[]"; //说明数组存在,但是没有元素。
 9 
10     StringBuilder b = new StringBuilder();
11     b.append('['); //"["
12     for (int i = 0; ; i++) {
13         b.append(a[i]); //"[24, 69, 80, 57, 13"
14         if (i == iMax)
15             //"[24, 69, 80, 57, 13]"
16             return b.append(']').toString();
17         b.append(", "); //"[24, 69, 80, 57, "
18     }
19 }

通过查看源码,我们知道一个原则:只要是对象,我们在使用该对象是否为null

3.  Arrays工具类的binarySearch方法底层:

1 public static  int binarySearch(int[]  a, int key);

使用样式:

1 int[] arr = {13, 24, 57, 69, 80};
2 System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));

上面方法的底层是:

1 public static int binarySearch(int[] a, int key) {
2     //a -- arr -- {13, 24, 57, 69, 80}
3     //key -- 577
4     return binarySearch0(a, 0, a.length, key);
5 }

追溯到binarySearch0方法的源码,如下:

 1 private static int binarySearch0(int[] a, int fromIndex, int toIndex,
 2                                  int key) {
 3     //a -- arr --  {13, 24, 57, 69, 80}
 4     //fromIndex -- 0
 5     //toIndex -- 5
 6     //key -- 577                           
 7                                  
 8                                  
 9     int low = fromIndex; //low=0
10     int high = toIndex - 1; //high=4
11 
12     while (low <= high) {
13         int mid = (low + high) >>> 1; //mid=2,mid=3,mid=4
14         int midVal = a[mid]; //midVal=57,midVal=69,midVal=80
15 
16         if (midVal < key)
17             low = mid + 1; //low=3,low=4,low=5
18         else if (midVal > key)
19             high = mid - 1;
20         else
21             return mid; // key found
22     }
23     return -(low + 1);  // key not found.
24 }
原文地址:https://www.cnblogs.com/hebao0514/p/4835814.html