AbstractTableModel getValueAt perfomance

I'm new to JTable , maybe I donโ€™t understand something.

Suppose ArrayList 1000 Students ( id, name, surname, age ). And I want to show all students in JTable . As I understand it, I have to create StudentTableModel that extends AbstractTableModel and set StudentTableModel to JTable . Therefore, we can consider StudentTableModel as an โ€œadapterโ€ between our ArrayList and table. On the Internet, I found an 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 with 1000 students (rows) and 4 fields (columns) we will run this switch 4000 times. Please explain what I'm doing wrong or tell you about the best solution.

+1
source share
2 answers

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

The package is false, but you must check the profile . JTable uses a template fly for cell rendering , so only visible cells will be considered. This simplified example illustrates an essential mechanism. This related example scales well in thousands of lines.

+2
source

You can store students in a Map that matches strings with student attributes.

 Map<Integer, Object[]> students; 

The method will look like this:

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

Source: https://habr.com/ru/post/969897/


All Articles