Convert ArrayList <Object []> to Object [] []

How to convert an ArrayList array to a two-dimensional array in Java?

Example:

ArrayList<String[]> results = new ArrayList<String[]>();
String [] columns = {a few strings};


JTable table = new JTable(results.toArray(), columns);

I get an error that JTable (Object [], Object []) is undefined.

+5
source share
2 answers

The method List<T>.toArray(T[])should do the job.

For instance:

List<String[]> list = ...
String[][] res = new String[list.size()][];
list.toArray(res);

or

List<String[]> list = ...
Object[][] res = new Object[list.size()][];
list.toArray(res);

If you use this overload rather than overload List<T>.toArray(), you can choose the actual type of array. It takes up one extra line of code, but if the type of the array is significant, this is the way to do it.

(Overloading List<T>.toArray()gives an array whose actual type is Object[]... regardless of the general type of the list or the actual type (s) of list items.)

+15

array.toArray() .

+3

All Articles