5

I have a collection of String[] values, for example:

ArrayList<String[]> values = new ArrayList<>();

String[] data1 = new String[]{"asd", "asdds", "ds"};
String[] data2 = new String[]{"dss", "21ss", "pp"};

values.add(data1);
values.add(data2);

And I need convert this to multidimensional array String[][]. When I try this:

String[][] arr = (String[][])values.toArray();

I get a ClassCastException.

How can I solve this problem?

2 Answers 2

7

What about this (this does not require Java 11 while toArray(String[][]::new) requires)

values.toArray(new String[0][0]);

That method is:

/**
 * Returns an array containing all of the elements in this list in proper
 * sequence (from first to last element); the runtime type of the returned
 * array is that of the specified array.  If the list fits in the
 * specified array, it is returned therein.  Otherwise, a new array is
 * allocated with the runtime type of the specified array and the size of
 * this list.
Sign up to request clarification or add additional context in comments.

Comments

4

No don't need to cast, check the doc, you can just use:

String[][] arr = values.toArray(new String[0][]);

Or if you are using Java 11

String[][] arr = values.toArray(String[][]::new);

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.