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.

2
  • I suggest you should use List<List<String>> matrixString. I mean you should use the List instead of ArrayList to declare the variable. And the answer of Robert Rouhani is fine. Commented May 15, 2012 at 3:10
  • Both answers are so good, it makes it real hard to pick which one I think has the right answer. Commented May 15, 2012 at 15:53

2 Answers 2

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()]);
Sign up to request clarification or add additional context in comments.

4 Comments

ToArray() should be toArray(new String[data.get(i).size()])
gah! I knew I'd run into an issue like that. I haven't touched Java in a few months in favor of C#... (I almost messed up .size() as .Count)
+1 Another way would be: converted[i] = new String[data.get(i).size()]; - data.get(i).toArray(converted[i]);
You have reminded me about the non-contiguous memory storage....and for that...with the solution, I think this is a very good answer
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.

2 Comments

+1 agree; there's a related example here.
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.

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.