java Arrays类

1.Arrays.sort():排序

    public void testArrayList(){
        int[] a = {9, 8, 7, 2, 3, 4, 1, 6, 5};
        Arrays.sort(a);
//        for(int arr:a) {
//            System.out.print(arr + " ");
//        }
        System.out.println(Arrays.toString(a));

    }

 执行结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.Arrays.binarySearch(Object[] a, Object key) :用二分查找算法在给定数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好的。如果查找值包含在数组中,则返回搜索键的索引;否则返回 (-(插入点) - 1)

    public void testArrayList(){
        int[] a = {9, 8, 7, 2, 3, 4, 1, 6, 5};
        Arrays.sort(a);
//        for(int arr:a) {
//            System.out.print(arr + " ");
//        }
        System.out.println(Arrays.toString(a));

        // 如果要想使用二分法查询的话,则必须是排序之后的数组
        int point = Arrays.binarySearch(a,3) ;	// 检索位置
        System.out.println("元素‘3’的位置在:" + point) ;


    }

执行结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
元素‘3’的位置在:2

3.fill(int[] a, int val):将指定的 int 值分配给指定 int 型数组指定范围中的每个元素。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)

    public void testArrayList(){
        int[] a = {9, 8, 7, 2, 3, 4, 1, 6, 5};

        //fill填充数组不是加在数组后面,而是将数组中的所有元素都重新赋一个新值
        Arrays.fill(a,3)	;// 填充数组
        System.out.print("数组填充:") ;
        System.out.println(Arrays.toString(a)) ;


    }

 执行结果:

数组填充:[3, 3, 3, 3, 3, 3, 3, 3, 3]

posted @ 2021-06-25 18:55  zhanchenglan  阅读(21)  评论(0编辑  收藏  举报