常用类--Arrays类--Arrays类概述及其常用方法

Arrays类概述及其常用方法

程序示例

import java.util.Arrays;
/*
        Arrays类概述及其常用方法
            该类包含用于操作数组的各种方法(如排序和搜索)。

            public static String toString(int[] a)
            public static void sort(int[] a)
            public static int binarySearch(int[] a,int key)
*/

public class ArraysDemo1 {
    public static void main(String[] args) {
        //定义一个数组
        int[] arr = {21, 32, 41, 431, 2, 41, 15};

      
      //public static String toString(int[] a)//遍历--重写了toString()方法
      
//      Java在数组中不提供重写的toString()方法
//      System.out.println(arr);
      
        String s = Arrays.toString(arr);
        System.out.println("数组:" + s);


        System.out.println("*****************************");
      
      //public static void sort(int[] a)//排序
      //没有返回值说明针对同一个数组进行操作
        Arrays.sort(arr);
        System.out.println("排序后的数组为:" + Arrays.toString(arr));

        System.out.println("******************************");
      
        //public static int binarySearch(int[] a,int key)//二分查找
        //[2, 15, 21, 32, 41, 41, 431]
        //二分查找的前提:序列是有序的
        int i = Arrays.binarySearch(arr, 32);
      //返回查找目标的索引
        System.out.println("二分查找32:" + i);//3
      //如果查找的目标不在被查找的数组中,返回的是什么呢?
        System.out.println("二分查找100:"+Arrays.binarySearch(arr,100));//-7----为什么呢?      
    }
}
/*
binarySearch()源码解析
*/

//a -- arr
//key -- 100
public static int binarySearch(int[] a, int key) {
    return binarySearch0(a, 0, a.length, key);
}

//a -- arr
//fromIndex -- 0
//toIndex -- 7
//key -- 100
//[2, 15, 21, 32, 41, 41, 431]
private static int binarySearch0(int[] a, int fromIndex, int toIndex,int key) {
    int low = fromIndex;  //0
    int high = toIndex - 1; //6

    while (low <= high) {
        int mid = (low + high) >>> 1; // 6>>>1=3 ,10>>>1=5,12>>>1=6
        int midVal = a[mid];  //32,41,431

        if (midVal < key)
            low = mid + 1; //4,6
        else if (midVal > key)
            high = mid - 1; //5
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found.  -(6+1)  ---> -7
}


posted @ 2021-12-16 23:25  赤兔胭脂小吕布  阅读(119)  评论(0)    收藏  举报