【问题标题】:Java; saving array of arrays into collection爪哇;将数组数组保存到集合中
【发布时间】:2016-01-16 22:38:25
【问题描述】:

所以我有这个数据

 { { 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[]>();

但我无法将该数据放入列表中

【问题讨论】:

  • 您尝试将哪些数据放入列表中。请分享更多的代码,而不仅仅是构造函数...
  • 重复的问题?
  • 是的,可能是这样,我在寻找答案时无法表达自己。无论如何感谢您的帮助。

标签: java arrays list arraylist


【解决方案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}
};
System.out.println(a[0][3]);

但是您不能创建任何可以使用[] 访问其值的集合类型。

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

List<int[]> a2 = Arrays.asList(
        new int[]{1, 3, 5, 3, 1},
        new int[]{3, 5, 6, 5, 1},
        new int[]{7, 2, 3, 5, 0},
        new int[]{12, 1, 5, 3, 0},
        new int[]{20, 6, 3, 6, 1},
        new int[]{20, 7, 4, 7, 1}
);

System.out.println(a2.get(0)[3]);

【讨论】:

  • 好吧其实我试过了,但我忘了添加其他索引,谢谢。但是,我仍然有兴趣将这些数据放入某种集合中。我不需要像 [i][j] 那样访问它。
  • 在这种情况下,您将不得不使用 ints 的盒装版本 - Integer。 IE。正如@elliott-frisch 所建议的那样
【解决方案2】:

您可以将其设为Integer[][] 并创建List&lt;List&lt;Integer&gt;&gt;。类似的,

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);

哪些输出(为此帖子格式化)

[[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]]

【讨论】:

    【解决方案3】:

    很难回答您在特定情况下真正需要什么。但总的来说,二维数组的列表等效项,我猜,您正在寻找的将是 List&lt;List&lt;Integer&gt;&gt; 类型,并且在 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())));
    

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      相关资源
      最近更新 更多