8. Arrays类

image
image

代码示例_排序

package com.baidu.www;

import java.util.Arrays;
import java.util.Comparator;

public class Test {
    public static void main(String[] args) {
        // 排序
        // sort重载,可以传入一个接口 Comparator 实现定制排序
        Integer arr[] = {1, -1, 7, 0, 89};
        // 定制排序 匿名内部类,要求实现 compare 方法
        // 接口编程 + 动态绑定 + 匿名内部类的综合使用
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
//                return o1 - o2; // 升序
                return o2 - o1; // 降序
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}

代码示例_其它

package com.baidu.www;

import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        // 二分搜索查找
        // 要求必须排序
        // 如果不存在该元素,就返回 -(low+1) key not found
        Integer[] arr = {1, 3, 90, 479, 567};
        int index = Arrays.binarySearch(arr, 478); // -4
        System.out.println(index);

        // 数组元素的复制
        // 如果拷贝的长度大于数组长度,自动添加null
        // 如果拷贝的长度小于0,异常
        // 底层调用 System.arraycopy
        Integer[] newArr = Arrays.copyOf(arr,arr.length+2); //[1, 3, 90, 479, 567, null, null]
        System.out.println(Arrays.toString(newArr));

        // 数组的填充
        Integer[] num = new Integer[]{9, 3,2};
        Arrays.fill(num, 99);
        System.out.println(Arrays.toString(num)); // [99, 99, 99]

        // equals比较元素是否完全一致
        Integer[] arr2 = {3, 90, 479, 567};
        System.out.println(Arrays.equals(arr, arr2));

        // asList 将一组值转换为List集合
        List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
        System.out.println(asList.getClass()); // class java.util.Arrays$ArrayList
    }
}
posted @ 2025-08-20 19:16  无敌美少女战士  阅读(8)  评论(0)    收藏  举报