ArrayList of arrays vs. array of ArrayLists vs. something similar
arraylist, arrays, data-structures, java, tablemodel
Solution
If the number of columns is fixed then your data is probably row-oriented or at least row-variable at which point each row should be an array. Fixed numbers of columns means you don't need to reallocate your array.
So your structure is:
List<Object[]> rows;
where the array element is one row.
There are several options for what your row object should be however:
- An array;
- A `List` or other `Collection`; or
- A custom object.
(3) can probably be done by using some kind of interface that allows you to query the number, type and name of columns.
Problem
I'm creating a TableModel which will have a fixed number of columns, but the number of rows will be changing (mostly, increasing as function of time). Which would be better approach to store the data, ``` ArrayList[] columns = new ArrayList[numberOfColumns]; // Each array element is one column. Fill each of them with a new ArrayList. ... public Object getValueAt(int row, int column) { return columns[column].get(row); } ``` i.e. creating an array of `ArrayList`s, each `ArrayList` representing one column, or: ``` ArrayList<Object[]> rows = new ArrayList<Object[]>(); // Each ArrayList element is one row. public Object getValueAt(int row, int column) { return rows.get(row)[column]; } ``` i.e. creating one ArrayList that holds arrays, each of which represent one row. Any ideas which of these is more efficient in terms of speed or storage? Alternative 1 requires extending N `ArrayList`s with each added row, while alternative 2 requires extending just one `ArrayList` but also creating a new array of length N (to represent the new row). Or is there an obvious, better solution?