【发布时间】:2016-01-11 17:06:06
【问题描述】:
所以我有这个充满对象的ArrayList,我需要将它转换为Object[][],以便轻松地将其放入JTable。
例子:
我有一个ArrayList<Animal>:
class Animal{
String color;
int age;
String eatsGrass;
// Rest of the Class (not important)
}
我想要的是一个具有以下列名称的 JTable:
Color - Age - Eats Grass?
我目前的方法是这样的:
List<Animal> ani = new ArrayList();
// Fill the list
Object[][] arrayForTable = new Object[ani.size()][3];
for (int i = 0 ; i < ani.size() ; i++){
for (int j = 0 ; j < 3 ; j++){
switch(j){
case 1 : arrayForTable[i][j] = ani.get(j).getColor();break;
case 2 : arrayForTable[i][j] = ani.get(j).getAge();break;
default : arrayForTable[i][j] = ani.get(j).getEatsGrass();break;
}
}
}
它工作正常,但有没有更简单的方法可以做到这一点。例如,我无法想象自己对具有 25 列的 JTable 使用相同的方法。
【问题讨论】:
-
更好的方法是使用适合您的支持数据类型的
TableModel -
@SteveKuo 是的,这是个好主意。
标签: java arrays optimization arraylist jtable