2

Do I have to loop through each element to convert ArrayList<String[]> to String[][] or is there a more efficient way?

1

2 Answers 2

8

Just get the contents as an array

List<String[]> list = new ArrayList<>();
...
String[][] array = list.toArray(new String[0][0]); // the size here is not important, the array is just an indication of the type to use
Sign up to request clarification or add additional context in comments.

1 Comment

It's better to specify the correct size as in list.toArray(new String[list.size()][]), otherwise a new array is instantiated with reflection.
3

You can use .toArray(T[]) for this.

public static void main(String[] args) {
    List<String[]> l = new ArrayList<String[]>();

    String[] a = {"lala", "lolo"};
    String[] b = {"lili", "lulu"};
    l.add(a);
    l.add(b);

    String[][] r = new String[l.size()][];
    r = l.toArray(r);

    for(String[] s : r){
        System.out.println(Arrays.toString(s));
    }
}

Output:

[lala, lolo]
[lili, lulu]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.