简体   繁体   English

如何在ArrayList中存储2D Integer数组?

[英]How to store a 2D Integer array in ArrayList?

I have this defined: List<Integer[][]> listOfInteger= new ArrayList<>(); 我已经定义了: List<Integer[][]> listOfInteger= new ArrayList<>();

How do I insert data into it? 如何将数据插入其中?

I have tried 我努力了

listOfInteger.add(new Integer[][](1,2));

and

List<Integer[][]> listOfInteger= Arrays.asList(new Integer({1, 2)});

But none works 但是没有办法

The short way is this: 简短的方法是这样的:

listOfInteger.add(new Integer[][] {{1, 2}, {1, 3}, {5, 7}});

But you could also just create the array and then fill it one by one. 但是您也可以只创建数组,然后一个一个地填充它。

You got confused by the dimensions you have defined an one dimensional ArrayLists which contains two-dimensional arrays as elements. 您对定义一维ArrayList的维感到困惑,其中一维ArrayLists包含二维数组作为元素。

    List<Integer[][]> listOfInteger = new ArrayList<Integer[][]>();
    // long version
    Integer[][] array2d = new Integer[2][2];
    array2d[0][0] = 3;
    array2d[0][1] = 2;
    array2d[1][0] = 4;
    array2d[1][1] = 2;
    listOfInteger.add(array2d);
    // short version
    listOfInteger.add(new Integer[][] { { 3, 2 }, { 4, 2 } });

After this operations your arrayList will contain two arrays, which contain integers with the same value 完成此操作后,您的arrayList将包含两个数组,其中包含具有相同值的整数

Have you tried the "double brace initialization"? 您是否尝试过“双括号初始化”?

List<Integer[][]> listOfInteger= new ArrayList() {{
    add(new Integer[][] { { 3, 2 }, { 4, 2 } });
    add(new Integer[][] { { 3, 2 }, { 4, 2 } });
    add(new Integer[][] { { 3, 2 }, { 4, 2 } });
}};

You can do this at the class level outside of methods. 您可以在方法之外的类级别上执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM