将二维数组转换为二维数组列表? [英] Transfer a Two-Dimensional array to Two-Dimensional ArrayList?

查看:94
本文介绍了将二维数组转换为二维数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

int[][] pattern = new int[][]{
        { 1, 1, 1, 1, 1, 1, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 0, 0, 4, 0, 0, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 1, 1, 1, 1, 1, 1 },
};

我需要将这个 2d 数组放入一个 2d ArrayList 中,以便我可以通过添加行和列来移动模式来操作它.例如,当我的方法要求移动 2 行和 2 列时,我将能够将模式移动到这样的位置:

I need to get this 2d array into a 2d ArrayList so i can manipulate it by adding rows and columns to move the pattern around. For example when my method calls for a shift of 2 rows and 2 columns i will be able to move the pattern to something like this:

        { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
        { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
        { 0, 0, 1, 1, 1, 1, 1, 1, 1 },
        { 0, 0, 1, 2, 0, 0, 0, 2, 1 },
        { 0, 0, 1, 0, 3, 0, 3, 0, 1 },
        { 0, 0, 1, 0, 0, 4, 0, 0, 1 },
        { 0, 0, 1, 0, 3, 0, 3, 0, 1 },
        { 0, 0, 1, 2, 0, 0, 0, 2, 1 },
        { 0, 0, 1, 1, 1, 1, 1, 1, 1 },

我只是想将二维数组放入二维数组列表中,任何帮助将不胜感激!

I'm just looking to get the 2d array into a 2d Arraylist any help will be greatly appreciated!

推荐答案

Case 1 很短,但是需要将原始类型转换为引用类型(int toInteger) 根据需要用于 Arrays.asList();

Case 1 It is short, but need to covert the primitive type to reference type (int to Integer) as needed for Arrays.asList();

Integer[][] pattern = new Integer[][]{
        { 1, 1, 1, 1, 1, 1, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 0, 0, 4, 0, 0, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 1, 1, 1, 1, 1, 1 },
};
List<List<Integer>> lists = new ArrayList<>();
for (Integer[] ints : pattern) {
    lists.add(Arrays.asList(ints));
}

情况 2 如果不想将原始类型转换为引用类型: (int[][] pattern = new int[][] to <代码>整数[][]模式=新整数[][])

Case 2 If you don't want to covert the primitive type to reference type: (int[][] pattern = new int[][] to Integer[][] pattern = new Integer[][])

List<List<Integer>> lists = new ArrayList<>();
for (int[] ints : pattern) {
    List<Integer> list = new ArrayList<>();
    for (int i : ints) {
        list.add(i);
    }
    lists.add(list);
}

这篇关于将二维数组转换为二维数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆