本文介绍了如何在java中将2Darray转换为2D ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了类似的问题,但仍然找不到适合我的案例的解决方案.所以基本上,我有一个名为array2D"的二维数组,我正在尝试将它们转换为二维数组列表.我尝试创建一个 arrayList 并使用 for 循环从我的 array2D 中复制每个元素,这是一个原始的二维数组.我想知道是否有任何干净有效的方法来做到这一点.

I have searched similar questions and I still cannot find the solution for my case. So basically, I have a 2D array called 'array2D' and I am trying to convert those into 2D arrayList. I tried to create an arrayList and used for loop to copy each of the elements from my array2D, which is a primitive 2D Array. I wonder if there is any clean and efficient way to do it.

这是我的代码:

    List<List<String>> arrayList2D = new ArrayList<List<String>>();
    List<String> eachRecord = new ArrayList<String>();

    for (int i=0; i< array2D.length; i++){
      for(int j =0; j<array2D[1].length; j++){
        eachRecord.add(String.valueOf(array2D[j]));
      }
      arrayList2D.add(eachRecord);
      eachRecord.clear();
    }

    System.out.println(Arrays.toString(arrayList2D.toArray()));

结果返回空的arrayList,这意味着我没有转换它们.

The result returns empty arrayList, which means I failed to convert them.

[[], [], [], [], [], [], [], [], [], [], [], [], [], []]

我怀疑无法填充新的ArrayList的原因是add方法使用错误,我也尝试过push方法,但编译错误.我想知道是否有任何干净有效的方法来做到这一点.

I suspect the reason why I failed to populate the new ArrayList is because of the wrong usage of add method, I have tried push method as well and it was compile error. I wonder if there is any clean and efficient way to do it.

推荐答案

我建议对您的代码进行 3 处改进.

I would suggest 3 improvements in your code.

  1. 使用array2D[i].length代替array2D[1].length.

使用 eachRecord.add(String.valueOf(array2D[i][j])); 而不是 eachRecord.add(String.valueOf(array2D[j]));.

array2D[index] 返回一个总数组.array2D[indexRow][indexCol] 返回这些索引处的对象.

array2D[index] returns a total array. array2D[indexRow][indexCol] returns the object at those indexes.

  1. 代替 clear() 在循环内启动 eachRecord 列表.

ListeachRecord = new ArrayList(); 在第一个 for 循环内.

List<String> eachRecord = new ArrayList<String>(); inside the first for loop.

String [][]array2D = {{"A", "B"}, {"C", "D"}, {"E", "F"}};
    List<List<String>> arrayList2D = new ArrayList<List<String>>();
    for (int i = 0; i < array2D.length; i++) {
        List<String> eachRecord = new ArrayList<String>();
        for (int j = 0; j < array2D[i].length; j++) {
            eachRecord.add(String.valueOf(array2D[i][j]));
        }
        arrayList2D.add(eachRecord);
    }
    System.out.println(arrayList2D);//[[A, B], [C, D], [E, F]]

如果你想添加整个数组,你可以使用 Arrays#asList 方法.

String[][] array2D = { { "A", "B" }, { "C", "D" }, { "E", "F" } };
    List<List<String>> arrayList2D = new ArrayList<List<String>>();
    for (int i = 0; i < array2D.length; i++) {
        List<String> eachRecord = Arrays.asList(array2D[i]);
        arrayList2D.add(eachRecord);
    }
    System.out.println(arrayList2D);

这篇关于如何在java中将2Darray转换为2D ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 00:16