java 13-2 Arrays工具类

1、Arrays:针对数组进行操作的工具类。比如说排序和查找。
    1:public static String toString(int[] a) 把数组转成字符串
    2:public static void sort(int[] a) 对数组进行排序
    3:public static int binarySearch(int[] a,int key) 二分查找

 1 import java.util.Arrays; //通过API查找,并不属于long包,所以需要导包
 2 public class ArraysDemo {
 3 public static void main(String[] args) {
 4 // 定义一个数组
 5 int[] arr = { 24, 69, 80, 57, 13 };
 6 
 7 // public static String toString(int[] a) 把数组转成字符串
 8 System.out.println("排序前:" + Arrays.toString(arr));
 9 
10 // public static void sort(int[] a) 对数组进行排序
11 Arrays.sort(arr);
12 System.out.println("排序后:" + Arrays.toString(arr));
13 
14 // [13, 24, 57, 69, 80] 为了演示二分查找方法的效果才先对数组进行排序,正常来说不能这样。
15 // public static int binarySearch(int[] a,int key) 二分查找
16 System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57));
17 System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));
18 }
19 }

2、 Arrays工具类的源码解析
    A、public static String toString(int[] a)
    B、public static void sort(int[] a) 底层是快速排序,知道就可以了。
    C、public static int binarySearch(int[] a,int key)

  开发原则:
    只要是对象,我们就要判断该对象是否为null。

  写的代码:

 1 int[] arr = { 24, 69, 80, 57, 13 };
 2 System.out.println("排序前:" + Arrays.toString(arr));
 3 
 4 toString的源码:
 5 public static String toString(int[] a) {
 6 //a -- arr -- { 24, 69, 80, 57, 13 }
 7 
 8 if (a == null)
 9 return "null"; //说明数组对象不存在
10 int iMax = a.length - 1; //iMax=4;
11 if (iMax == -1)
12 return "[]"; //说明数组存在,但是没有元素。
13 
14 StringBuilder b = new StringBuilder();
15 b.append('['); //"["
16 for (int i = 0; ; i++) { //中间为空,则默认为true,永远进行
17 b.append(a[i]); //"[24, 69, 80, 57, 13"
18 if (i == iMax) //限制了循环次数
19 //"[24, 69, 80, 57, 13]"
20 return b.append(']').toString();
21 b.append(", "); //"[24, 69, 80, 57, "
22 }
23 }
24 -----------------------------------------------------
25 写的代码:
26 int[] arr = {13, 24, 57, 69, 80};
27 System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));
28 
29 binarySearch的源码:
30 public static int binarySearch(int[] a, int key) {
31 //a -- arr -- {13, 24, 57, 69, 80}
32 //key -- 577
33 return binarySearch0(a, 0, a.length, key);
34 }
35 
36 private static int binarySearch0(int[] a, int fromIndex, int toIndex,
37 int key) {
38 //a -- arr -- {13, 24, 57, 69, 80}
39 //fromIndex -- 0
40 //toIndex -- 5
41 //key -- 577 
42 
43 
44 int low = fromIndex; //最小索引low=0
45 int high = toIndex - 1; //最大索引high=4
46 
47 while (low <= high) {
48 //无符号右移,相当于(low+hith)/2
49 int mid = (low + high) >>> 1; //mid=2,mid=3,mid=4
50 int midVal = a[mid]; //midVal=57,midVal=69,midVal=80
51 
52 if (midVal < key)
53 low = mid + 1; //low=3,low=4,low=5
54 else if (midVal > key)
55 high = mid - 1;
56 else
57 return mid; // key found
58 }
59 return -(low + 1); // key not found.
60 }
何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5879668.html