AbstractTableModel getValueAt perfomance

∥☆過路亽.° 提交于 2019-12-02 08:42:50

问题


I am newbie in JTable, maybe I don't understand something.

Let's suppose I have ArrayList of 1000 Students (id, name, surname, age). And I want to show all students in JTable. As far as I understood I must create StudentTableModel that extends AbstractTableModel and set StudentTableModel to JTable. Therefore we can consider StudentTableModel as an "adapter" between our ArrayList and the table. On the internet I found such example implementation of getValueAt:

 public Object getValueAt(int row, int col) {
      Student student = arrayList.get(row);
      switch (col) {
      case 0:
        return student.getId();
      case 1:
        return student.getName();
      case 2:
        return student.getSurname();
      case 3:
        return student.getAge();
      }
    }

The problem is that having 1000 students (rows) and 4 field (columns) we will run this switch 4000 times. Please explain what I do wrong or tell about a better solution.


回答1:


Having 1000 students (rows) and 4 field (columns), we will run this switch 4000 times.

The premise is false, but you should profile to verify. JTable uses the flyweight pattern for cell rendering, so only visible cells will be examined. This simplified example illustrates the essential mechanism. This related example scales well into the thousands of rows.




回答2:


You can store students in a Map which maps row to student attributes.

Map<Integer, Object[]> students;

The method will look so:

public Object getValueAt(int row, int col) {
    return students.get(row)[col];
}


来源:https://stackoverflow.com/questions/23511824/abstracttablemodel-getvalueat-perfomance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!