Java嵌套列表到数组转换

MrG*_*MrG 9 java arrays list jtable

将数据从嵌套列表转换为对象数组(可以用作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);
}
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Pat*_*ick 10

//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);
}
Run Code Online (Sandbox Code Playgroud)

我对JTable一无所知,但将列表列表转换为数组可以用几行完成.


Mic*_*ers 7

对于JTable特别,我建议子类AbstractTableModel,如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这是最基本的实现; 为简洁起见,省略了错误检查.

使用这样的模型,您不必担心无意义的转换Object[][].