【问题标题】:How can I convert a List<int[]> to a 2D array?如何将 List<int[]> 转换为二维数组?
【发布时间】:2017-11-06 11:28:36
【问题描述】:

我有一个这样声明的数组列表:

List<int[]> ls = new ArrayList<int[]>();

在这里,我试图保留一个包含这样的数组的列表: [ [1,2,3] ,[2,3],[4,5] ]

要将数组添加到此列表中,我在 for 循环中执行此操作:

int[] a = new int[2];
a[0] = arr[i];
a[1] = arr[i]+k;
ls.add(a);

我想将此数组列表转换为具有 1 行和 list.size 的矩阵中的列,如下所示:

[[0, -1], [-1, -2], [2, 1], [1, 0]]

我该怎么做?

谢谢!

【问题讨论】:

    标签: java list matrix


    【解决方案1】:

    简单,调用toArray

    // new double-dimension int array
    //                   | conversion here
    //                   |                  | specifying 1st dimension's size as list's 
    //                   |                  | size
    int[][] converted = ls.toArray(new int[ls.size()][]);
    
    // test it
    System.out.println(Arrays.deepToString(converted));
    

    【讨论】:

    • 你好。不应该是 int[][] 转换 = ls.toArray(new int[1][ls.size()]);
    • @MarianaMitru 没有。考虑第一个维度是列表自身的大小,即您有多少 int[]s。第二个维度可能是可变的,具体取决于您的每个 int[]s 中的内容。
    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多