How to convert an ArrayList of String arrays into a 2D string array

时间:2015-05-04 19:43:19

标签: java arrays string arraylist

I have an ArrayList<String[]> array_list
I want to convert it into a 2D String array say result such that first string array in array_list is in result[0]. Also I want to have first string in result to be equal to string equal.
i.e. If first array in array_list has ["A","B","C"] and my string equal is "D" my result[0] should be ["D","A","B","C"]

I tried:

ArrayList<String[]> result = new ArrayList<String[]>();
// I'm getting value of result from a function
String[][] array = new String[result.size()][]; 
int j =0;
for (String[] arrs : result)
{
    System.out.println(j);
    String arr = n;//I have taken n as parameter for the function
    array[j][0] = arr;
    int i =1;
    for(String o : arrs)
    {
        array[j][i] = o;
        i++;
    }
    j++;
}

but this gives java.lang.NullPointerException.

2 个答案:

答案 0 :(得分:3)

array[j] is never initialized. You have to first assign a String[] instance to array[j] before using it.

Add the following line at the beginning of your outer for-loop (before array[j][0] = arr):

array[j] = new String[arrs.length + 1];

答案 1 :(得分:0)

这是一个替代方案(标题中的问题)。

我最初的想法是做以下事情;

String[][] array = (String[][]) result.toArray()

但结果却令人讨厌ClassCastException告诉我们无法将Object数组转换为String数组。

所以,这就是Arrays类(java.util.Arrays)派上用场的地方。

String[][] array = Arrays.copyOf(result.toArray(), result.toArray().length, String[][].class);

或者花哨的Java 8;

String[][] array = Arrays.stream(result.toArray()).toArray(String[][]::new);