I have a base class which includes the following line to sort my objects ArrayList:
Collections.sort(objects, SortObjectList);
It also includes the following class definition to define the sort:
private class SortObjectList implements Comparator<T>
{
public int compare(T lhs, T rhs)
{
return lhs.name.compareToIgnoreCase(rhs.name);
}
}
In order to allow a derived class to sort using different criteria, I have implemented the following:
Collections.sort(objects, getSortObjectClass());
and
public Comparator<T> getSortObjectClass() {
return new SortObjectList();
}
private class SortObjectList implements Comparator<T>
{
public int compare(T lhs, T rhs)
{
return lhs.name.compareToIgnoreCase(rhs.name);
}
}
I then override the sort in the derived class as follows:
@Override
public Comparator<MyDataClass> getSortObjectClass() {
return new SortObjectList();
}
private class SortObjectList implements Comparator<MyDataClass>
{
public int compare(MyDataClasslhs, MyDataClassrhs)
{
return lhs.seqNo - rhs.seqNo;
}
}
Which orders by seqNo rather than name.
It works, but seems a bit clunky. Does anyone know of a more elegant solution?
Well you can make it slightly more compact using an anonymous inner class:
But that’s about as compact as it gets in Java.
(Note that your comparison above will give the wrong result on overflow, by the way.)