简体   繁体   中英

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.

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,  , !]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM