Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ArrayList<String[]> to multidimensional array String[][]?

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?

like image 727
stfxc Avatar asked Feb 14 '21 11:02

stfxc


People also ask

How do you make an ArrayList into a 2D array?

You can use toArray() method to convert an ArrayList to an array. Since you have ArrayList within ArrayList, you will need to iterate over each element and apply this method.

Can an ArrayList be multidimensional?

Overview. Creating a multidimensional ArrayList often comes up during programming. In many cases, there is a need to create a two-dimensional ArrayList or a three-dimensional ArrayList. In this tutorial, we'll discuss how to create a multidimensional ArrayList in Java.

How do you convert an ArrayList to a String?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.


2 Answers

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.
like image 65
ch271828n Avatar answered Oct 19 '22 04:10

ch271828n


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);
like image 4
YCF_L Avatar answered Oct 19 '22 04:10

YCF_L