0

My problem is TableRowSorter is incorrectly sorting for double & integer, I've been searching and tried almost all solution listed below.

-using getColumnClass()

-using setComparator()

@Override
public Class<?> getColumnClass(int column)
{
if (column == 4)
  return Integer.class;
else
      return String.class;
  }
};

sorter.setComparator(4, new Comparator<Integer>() {
@Override
  public int compare(Integer o1, Integer o2) {
      int len1 = o1.toString().length();
      int len2 = o2.toString().length();
      if (len1==len2) {
          return o1.compareTo(o2);
      } else {
          return len1-len2;
      }
  }
})
Armali
  • 18,255
  • 14
  • 57
  • 171
  • There is no need to create a custom comparator. JTable already has a sorter for Integer objects. All you need to do is override the getColumnClass() method of your TableModel to return Integer.class and make sure you store Integer objects in the TableModel. See the `TableSortDemo` from the Swing tutorial on [Sorting and Filtering](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting) for a working example. If you still have a problem, then post a proper [mcve] that demonstrates the problem. – camickr Oct 22 '18 at 18:18
  • For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). Like seen [here](https://stackoverflow.com/a/6592538/418556). – Andrew Thompson Oct 22 '18 at 21:00

1 Answers1

1

This is just to correct you for your implementation of compare method,

Instead of your current method,

  @Override
  public int compare(Integer o1, Integer o2) {
      int len1 = o1.toString().length();
      int len2 = o2.toString().length();
      if (len1==len2) {
          return o1.compareTo(o2);
      } else {
          return len1-len2;
      }
  }

You should just use Integer class's compare method, like this. Easy, safe and manageable.

  @Override
  public int compare(Integer o1, Integer o2) {
      return Integer.compare(o1, o2);
  }

This way it won't let you run into integer overflow cases if you try to do something like len1-len2. Imagine if len1 is already lowest negative integer and you further try to subtract something from it?

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36