java中数组操作,正序,逆序,子数组、自定义排序

// 数组定义,初始化
        int[] array = new int[]{1, 2, 2, 1};
        int[] dest = new int[10];
        Integer[] soul = new Integer[]{10,3,1,5};

        // 获取子数组
        int[] subArray = Arrays.copyOf(array, 3);
        int[] subarr = Arrays.copyOfRange(array, 1, 3);

        // 数组复制
        System.arraycopy(array, 0, dest, 0, 2);

        // 排序,Arrays.sort默认是升序排列
        Arrays.sort(array); // 默认升序

        // 编译错误,指定array order,但是指定排序的话必须是包装类型,不支持基本类型
        // Arrays.sort(array, Collections.reverseOrder());

        // 包装类型,降序排列
        Arrays.sort(soul, Collections.reverseOrder()); // 降序排列
        Arrays.sort(soul, (v1, v2) -> v2 - v1); // 使用lambda表达式设置排列顺序

        // 注:Arrays.asList 可以将array转为list

 数组元素自定义排序

        // idea里提示可以优化,优化后的是这种
        Arrays.sort(arr, Comparator.comparingInt(o -> o[0]));
        // lambda表达式
        Arrays.sort(arr, (o1, o2) -> (o1[0] - o2[0]));
     // 原始比较器
        Arrays.sort(arr, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

 

posted @ 2022-07-05 11:21  江湖凶险  阅读(648)  评论(0编辑  收藏  举报