Java nested list to array conversion
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[][]
.
//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.