3

It looks like the JTable construct likes String[][]... but I like to use smarter containers until I have to use something else. been using ArrayList<ArrayList<String>>, now I need to make JTable happy with String[][].

I found a real easy way to convert an ArrayList<String> to a String[] using toArray(), but not finding the easy converter for multidimensional arrays.

I want to go from ArrayList<ArrayList<String>> to String[][] in the least number of lines.

I have been searching the library and cannot seem to find this converter, and hoping someone could suggest a good solution for this.

Thanks in advance.

Robert Rouhani
  • 14,512
  • 6
  • 44
  • 59
Bruce Chidester
  • 621
  • 1
  • 5
  • 16
  • I suggest you should use `List> matrixString`. I mean you should use the `List` instead of `ArrayList` to declare the variable. And the answer of Robert Rouhani is fine. –  May 15 '12 at 03:10
  • Both answers are so good, it makes it real hard to pick which one I think has the right answer. – Bruce Chidester May 15 '12 at 15:53

2 Answers2

7

ArrayList<ArrayList<String>> isn't contiguous in memory. That is the second array list stores an array of references to ArrayList<String>s, and in each of those ArrayLists, there can be an array larger than the amount of items you put into it.

So the only real way to do this is by iterating:

ArrayList<ArrayList<String>> data;

//...

String[][] converted = new String[data.size()][];
for (int i = 0; i < converted.length; i++)
    converted[i] = data.get(i).toArray(new String[data.get(i).size()]);
Robert Rouhani
  • 14,512
  • 6
  • 44
  • 59
6

You probably want to look at implementing your own table model: JTable(TableModel dm)

You can create a class that extends AbstractTableModel and delegates to a List, or any other suitable data structure.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
barry
  • 201
  • 1
  • 4
  • +1 agree; there's a related example [here](http://stackoverflow.com/a/9134371/230513). – trashgod May 15 '12 at 05:19
  • Even though you did not show how to convert the data, your answer points me in a much better direction, and for that, I believe you have the best answer. – Bruce Chidester May 15 '12 at 15:58