2

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.

jbchichoko
  • 1,574
  • 2
  • 12
  • 16

2 Answers2

4

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
}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Ahh thank you. Adding ".toArray(new char [0][0])" worked. But could you explain how that "new char [0][0]" is affecting the solution ? newbie here :) – jbchichoko Feb 28 '12 at 14:47
  • Check the javadoc here: http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray%28T[]%29 – assylias Feb 28 '12 at 14:49
2

Something like this:

public static void main(String[] args) {
    List<char []> list = new ArrayList<char []>();
    list.add("hello".toCharArray());
    list.add("world !".toCharArray());
    char[][] xss = list.toArray(new char[0][0]);
    for (char[] xs : xss) {
        System.out.println(Arrays.toString(xs));
    }
}

Output:

[h, e, l, l, o]
[w, o, r, l, d,  , !]
MarcoS
  • 13,386
  • 7
  • 42
  • 63