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

问题描述

我搜索了类似的问题,但仍然找不到适合我的案例的解决方案.所以基本上,我有一个名为'array2D'的2D数组,我正在尝试将其转换为2D arrayList.我试图创建一个arrayList并用于循环以复制来自array2D的每个元素,而array2D是原始的2D Array.我想知道是否有任何干净有效的方法.

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列表.

List<String> eachRecord = new ArrayList<String>();在第一个for循环内.

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方法.


If you want to add whole array you could use Arrays#asList method.

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