views:

1401

answers:

2

What is the most efficient way to convert data from nested lists to an object array (which can be used i.e. as data for JTable)?

List<List> table = new ArrayList<List>();

for (DATAROW rowData : entries) {
    List<String> row = new ArrayList<String>();

    for (String col : rowData.getDataColumn())
        row.add(col);

    table.add(row);
}

// I'm doing the conversion manually now, but
// I hope that there are better ways to achieve the same
Object[][] finalData = new String[table.size()][max];
for (int i = 0; i < table.size(); i++) {
    List<String> row = table.get(i);

    for (int j = 0; j < row.size(); j++)
        finalData[i][j] = row.get(j);
}

Many thanks!

+7  A: 

For JTable in particular, I'd suggest subclassing AbstractTableModel like so:

class MyTableModel extends AbstractTableModel {
    private List<List<String>> data;
    public MyTableModel(List<List<String>> data) {
        this.data = data;
    }
    @Override
    public int getRowCount() {
        return data.size();
    }
    @Override
    public int getColumnCount() {
        return data.get(0).size();
    }
    @Override
    public Object getValueAt(int row, int column) {
        return data.get(row).get(column);
    }
    // optional
    @Override
    public void setValueAt(Object aValue, int row, int column) {
        data.get(row).set(column, aValue);
    }
}

Note: this is the most basic implementation possible; error-checking is omitted for brevity.

Using a model like this, you don't have to worry about pointless conversions to Object[][].

Michael Myers
Good answer. However, double-check that the data passed to this model isn't visible elsewhere, and prone to ninja-editing. It probably isn't, but if it is, it may need to be cloned here.
Paul Brinkley
Good point. I thought of that, but DefaultTableModel actually doesn't check either (it uses Vectors). Anyway, this is the most basic implementation possible. ;)
Michael Myers
+1  A: 
//defined somewhere
List<List<String>> lists = ....

String[][] array = new String[lists.size()][];
String[] blankArray = new String[0];
for(int i=0; i < lists.size(); i++) {
    array[i] = lists.get(i).toArray(blankArray);
}

I don't know anything about JTable, but converting a list of lists to array can be done with a few lines.

Patrick