문제

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.

도움이 되었습니까?

해결책

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
}

다른 팁

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,  , !]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top