Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList of arrays vs. array of ArrayLists vs. something similar

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 ArrayLists, 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 ArrayLists 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?

like image 646
Joonas Pulakka Avatar asked Feb 23 '10 08:02

Joonas Pulakka


1 Answers

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:

  1. An array;
  2. A List or other Collection; or
  3. 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.

like image 62
cletus Avatar answered Sep 17 '22 23:09

cletus