Question

I have a custom AbstractTableModel

That model stores the data in a HashMap. So for my method for getValueAt(int rowIndex, int columnIndex)

I do

new ArrayList<Object>(data.values()).get(index);

However my data has over 2000 entries, so doing this every single time whenever I have to get the data for my table creates a huge performance hit.

So what solution can you recommend?

Should I try using List to store all my data in instead of HashMap?
What is the accepted standard for storing data when using table models?

Thanks to anyone for their suggestion, and I aplogize for what might be a stupid question, but I am not too great when it comes to tables and how to store data in them.

Was it helpful?

Solution

A HashMap doesn't generally make a good fit for a table model because the table needs the ability to access data at an row/col location.

A ArrayList of ArrayLists is a reasonable way to store a table model. This still gives you fast access. Getting to a particular row is a constant time lookup, and then getting the column is also a constant time lookup.

If you don't want the overhead of the lists, you can always store the data in a 2D array.

OTHER TIPS

Yes, the code you sight is going to suck in performance terms - for every cell you render, you're creating a new ArrayList based on the values in your Map (you can do the math).

At the very least, do the list creation once, probably in the constructor of your table model, like this (which assumes you've got some arbitary object, that you don't mention in your question, as the values of the map):

public class MyTableModel extends AbstractTableModel
{
  private static final int COLUMN_0 = 0;
  private static final int COLUMN_1 = 1;

  private List<MyObject> data;

  public MyTableModel(Map<?, MyObject> data)
  {
    this.data = new ArrayList<MyObject>(data.values());
  }

  public Object getValueAt(int rowIndex, int columnIndex)
  {
    switch (columnIndex)
    {
      case COLUMN_0: return this.data.get(rowIndex).getColumn0();
      case COLUMN_1: return this.data.get(rowIndex).getColumn1();
      ...
      case COLUMN_N: return this.data.get(rowIndex).getColumnN();
    }

     throw new IllegalStateException("Unhandled column index: " + columnIndex);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top