【问题标题】:Easy way to make an Object[][] from an ArrayList<Object> with the fields of Objects [duplicate]使用 Objects 字段从 ArrayList<Object> 创建 Object[][] 的简单方法 [重复]
【发布时间】:2016-01-11 17:06:06
【问题描述】:

所以我有这个充满对象的ArrayList,我需要将它转换为Object[][],以便轻松地将其放入JTable

例子:

我有一个ArrayList&lt;Animal&gt;

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


【解决方案1】:

将此添加到您的 Animal 课程中。

public Object[] getDataArray() {
    return new Object[]{color, age, eatsGrass};
}

然后,使用TableModel

String columns[] = {"Color", "Age", "Eats Grass?"}; 

DefaultTableModel tableModel = new DefaultTableModel(columns, 0);

for (Animal animal : ani) {
    tableModel.addRow(animal.getDataArray());
}

JTable animalTable = new JTable(tableModel);

【讨论】:

  • 谢谢!使用 tableModel 无疑是​​最好的方法。接受!
【解决方案2】:

在您的 Animal 类中添加一个新方法肯定会对您有所帮助:

public Object[] getAttributesArray() {
    return new Object[]{color, age, eatsGrass};
}

然后:

for (int i = 0; i < ani.size(); i++){
    arrayForTable[i] = ani.get(i).getAttributesArray();
}

【讨论】:

  • 谢谢!真是个好主意!
【解决方案3】:

刚刚呢

   for (int i = 0 ; i < ani.size() ; i++){
            arrayForTable[i] = new Object[]{
             ani.get(i).getColor(), ani.get(i).getAge(),ani.get(i).getEatsGrass()};
}

【讨论】:

  • 赞成,因为它回答了问题,但是如果我有 100 个字段呢?
  • @YassinHajaj 如果您的班级动物将有 100 个字段,那么任何解决方案都会遇到同样的问题。
【解决方案4】:
for(int i = 0; i < ani.size(); i++) {
Animal animal = ani.get(i);
arrayForTable[i] = new Object[] {animal.getColor(), animal.getAge(), animal. getEatsGrass()};
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多