Search code examples
javaarraylistnullpointerexceptionmultidimensional-arraytoarray

2D ArrayList to a normal array java


Basically, I am creating a dynamic 2d ArrayList.

private ArrayList<char[]> myArray;

This code below is done in loop. A few random strings of the "same length" is given to store the all the characters in array.

while (body)

char[] temp = myString.toCharArray();
myArray.add(temp);

So after all the characters are inserted into the ArrayList, I want to convert myArray into a normal array. (why? because it is going to be useful in future) And I think I am doing it wrong here:

charArray = (char[][]) myArray.toArray();
//declaration of 'charArray' is already done at the start of the class.

So the problem is when I try to print the whole 'charArray' just to check, or any elements, I get an "java.lang.NullPointerException" error.

So how do I covert the 2d ArrayList into a normal array ? I tried many different sources but didn't help.

Thank you.


Solution

  • Not sure if you want a char[] or a char[][] in the end. See below both options:

    public static void main(String... args) throws Exception {
        List<char[]> myArray = new ArrayList<char[]>();
        myArray.add("string1".toCharArray());
        myArray.add("string2".toCharArray());
        myArray.add("string3".toCharArray());
    
        char[][] charArray2D = myArray.toArray(new char[0][0]);
        System.out.println(charArray2D.length); //prints 3
    
        StringBuilder s = new StringBuilder();
        for (char[] c : myArray) {
            s.append(String.copyValueOf(c));
        }
        char[] charArray1D = s.toString().toCharArray();
        System.out.println(charArray1D.length); //prints 21
    }