将数据从嵌套列表转换为对象数组(可以用作JTable的数据)的最有效方法是什么?
Listtable = new ArrayList
(); for (DATAROW rowData : entries) { List
row = new ArrayList (); 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 row = table.get(i); for (int j = 0; j < row.size(); j++) finalData[i][j] = row.get(j); }
非常感谢!
//defined somewhere List> 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); }
我对JTable一无所知,但将列表列表转换为数组可以用几行完成.
对于JTable
特别,我建议子类AbstractTableModel
,如下所示:
class MyTableModel extends AbstractTableModel { private List> data; public MyTableModel(List
> 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); } }
注意:这是最基本的实现; 为简洁起见,省略了错误检查.
使用这样的模型,您不必担心无意义的转换Object[][]
.