JAVA将数组的数组保存到集合中

JAVA将数组的数组保存到集合中,java,arrays,list,arraylist,Java,Arrays,List,Arraylist,所以我有这些数据 { { 1, 3, 5, 3, 1 }, { 3, 5, 6, 5, 1 }, { 7, 2, 3, 5, 0 }, { 12, 1, 5, 3, 0 }, { 20, 6, 3, 6, 1 }, { 20, 7, 4, 7, 1 } } 我想把它保存到某种集合、列表或集合中。因此,如果该集合名为List,如果我要键入List[0][3],它将引用int 4。 我试过了 ArrayList<int[]> myNumberLi

所以我有这些数据

 { { 1,  3, 5, 3, 1 },
   { 3,  5, 6, 5, 1 },
   { 7,  2, 3, 5, 0 },
   { 12, 1, 5, 3, 0 },
   { 20, 6, 3, 6, 1 }, 
   { 20, 7, 4, 7, 1 } }
我想把它保存到某种集合、列表或集合中。因此,如果该集合名为
List
,如果我要键入
List[0][3]
,它将引用int 4。 我试过了

ArrayList<int[]> myNumberList = new ArrayList<int[]>();
ArrayList myNumberList=new ArrayList();

但是我在将数据放入列表时遇到了问题。

数组访问操作符
[]
仅适用于数组。所以只能创建二维数组

int a[][] = new int[][]{
        {1, 3, 5, 3, 1},
        {3, 5, 6, 5, 1},
        {7, 2, 3, 5, 0},
        {12, 1, 5, 3, 0},
        {20, 6, 3, 6, 1},
        {20, 7, 4, 7, 1}
};
System.out.println(a[0][3]);
但是您不能创建任何类型的集合来使用
[]
访问其值

Yoy仍然可以使用数组列表。但您必须使用get()方法为第一个维度编制索引

List a2=Arrays.asList(
新的int[]{1,3,5,3,1},
新的int[]{3,5,6,5,1},
新的int[]{7,2,3,5,0},
新的int[]{12,1,5,3,0},
新的int[]{20,6,3,6,1},
新int[]{20,7,4,7,1}
);
System.out.println(a2.get(0)[3]);

您可以将其设置为
整数[][]
并创建一个
列表。大概

Integer[][] arr = { { 1, 3, 5, 3, 1 }, { 3, 5, 6, 5, 1 }, 
        { 7, 2, 3, 5, 0 }, { 12, 1, 5, 3, 0 }, { 20, 6, 3, 6, 1 }, 
        { 20, 7, 4, 7, 1 } };
System.out.println(Arrays.deepToString(arr));
List<List<Integer>> al = new ArrayList<>();
for (Integer[] inArr : arr) {
    al.add(Arrays.asList(inArr));
}
System.out.println(al);

很难回答您在特定情况下真正需要什么。但在一般情况下,我猜您正在寻找的二维数组的等效列表将是
list
类型,在java-8中,您可以用以下方式转换它:

    int a[][] = new int[][]{
            {1, 3, 5, 3, 1},
            {3, 5, 6, 5, 1},
            {7, 2, 3, 5, 0},
            {12, 1, 5, 3, 0},
            {20, 6, 3, 6, 1},
            {20, 7, 4, 7, 1}};

    List<List<Integer>> l2 = new ArrayList<>();
    Stream.of(a).forEach(a1 -> l2.add(Arrays.stream(a1).boxed().collect(Collectors.toList())));
int a[][]=新int[][]{
{1, 3, 5, 3, 1},
{3, 5, 6, 5, 1},
{7, 2, 3, 5, 0},
{12, 1, 5, 3, 0},
{20, 6, 3, 6, 1},
{20, 7, 4, 7, 1}};
列表l2=新的ArrayList();
Stream.of(a).forEach(a1->l2.add(Arrays.Stream(a1).boxed().collect(Collectors.toList()));

您尝试将哪些数据放入列表中。请分享更多的代码,而不仅仅是构造器…重复的问题?可能是重复的是的,可能是,当我在寻找答案时,我无法清楚地表达自己。无论如何,谢谢你的帮助。好的,实际上我试过了,但我忘了添加其他索引,无论如何,谢谢。然而,我仍然有兴趣将这些数据收集起来。我不需要像[I][j]那样访问它。在这种情况下,您将不得不使用整型int的盒装版本-
Integer
。即@elliott frisch建议的
[[1, 3, 5, 3, 1], [3, 5, 6, 5, 1], [7, 2, 3, 5, 0], 
                  [12, 1, 5, 3, 0], [20, 6, 3, 6, 1], [20, 7, 4, 7, 1]]
[[1, 3, 5, 3, 1], [3, 5, 6, 5, 1], [7, 2, 3, 5, 0], 
                  [12, 1, 5, 3, 0], [20, 6, 3, 6, 1], [20, 7, 4, 7, 1]]
    int a[][] = new int[][]{
            {1, 3, 5, 3, 1},
            {3, 5, 6, 5, 1},
            {7, 2, 3, 5, 0},
            {12, 1, 5, 3, 0},
            {20, 6, 3, 6, 1},
            {20, 7, 4, 7, 1}};

    List<List<Integer>> l2 = new ArrayList<>();
    Stream.of(a).forEach(a1 -> l2.add(Arrays.stream(a1).boxed().collect(Collectors.toList())));