|
Comparators |
Top Previous Next |
SortTableModel sorts the data by comparing the cell values with each other. The comparison is performed with special objects, called Comparators, which implement the java.util.Comparator interface.
Comparators compare two objects passed as an argument in the method:
public int compare(Object o1, Object o2);
, and return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
We have implemented several comparators for all the common objects. These can be found in the com.sciapp.comparators package:
BooleanComparator: for Boolean values.
DateComparator: for Dates.
StringComparator: for Strings.
CaseInsensitiveStringComparator: for Strings, ignoring case differences.
GeneralComparator: for all other objects that implement the java.lang.Comparable interface.
When sorting is requested for a column, SortTableModel will try to retrieve a Comparator for that column by calling the method:
public Comparator getComparator(int column);
If this method returns null, SortTableModel will then invoke the method:
public Comparator getDefaultComparator(Class columnClass);
, by first retrieving the class of the column.
If this method returns null as well, then a NullPointerException will be thrown. To avoid this, you need to install comparators with:
public void setComparator(int column, Comparator comparator);
public void setDefaultComparator(Class columnClass, Comparator comparator);
By default, SortTableModel installs comparators for the most common classes. This is done in the method:
protected void createDefaultComparators();
Note: Comparators are also used by TreeTableModel in order to group the tabular data.