Shaik Asief Hussain
Shaik Asief Hussain

Reputation: 17

JTable sorter incorrect sorting on integer & double

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;
      }
  }
})

Upvotes: 0

Views: 105

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

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?

Upvotes: 1

Related Questions