Java基础-按最大长度拆分数组

2023-07-24 187点热度 0人点赞 0条评论

需求说明

有一个ArrayList,里面的元素很多,需要把这个ArrayList拆分成若干成最大长度是200个元素的子数组。

实现

public static void main(String[] args) {
        ArrayList<Integer> originalList = new ArrayList<>();
        // 添加一些元素到originalList

        int maxLength = 200;
        List<List<Integer>> subArrays = splitArrayList(originalList, maxLength);

        // 打印子数组
        for (List<Integer> subArray : subArrays) {
            System.out.println(subArray);
        }
    }

    public static <T> List<List<T>> splitArrayList(List<T> originalList, int maxLength) {
        List<List<T>> subArrays = new ArrayList<>();
        int fromIndex = 0;
        int toIndex = Math.min(maxLength, originalList.size());

        while (fromIndex < originalList.size()) {
            subArrays.add(originalList.subList(fromIndex, toIndex));
            fromIndex = toIndex;
            toIndex = Math.min(toIndex + maxLength, originalList.size());
        }

        return subArrays;
    }
}

在这个示例中,我们首先创建了一个originalList,它是包含大量元素的ArrayList。然后,我们定义了maxLength,即子数组的最大长度为200。接下来,我们调用splitArrayList()方法来拆分ArrayList并返回一个包含子数组的List。最后,我们打印每个子数组。

请注意,在splitArrayList()方法中,我们使用subList()方法来获取原始ArrayList的子列表。我们使用fromIndex和toIndex变量来指定子列表的起始索引和结束索引。通过不断递增这些索引,我们可以在循环中获取不同的子列表。

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论