Not quite sure how I should attack this. I need to create a Comparator for a class called Record. These records have a time I will use, but if the time is the same, I need to order them depending on their type. Say for example we have the following Record subtypes:
AaRecordBbRecordCcRecordDdRecord
Now, given a collection with a number of these, I need to order them so that for example all CcRecord come before BbRecord followed by AaRecord and finally DdRecord. What is a good and clean way of doing this?
Just to be clear, I can’t use the names of the types to do this, as they could be anything. It’s going to be used to process a list of records in the correct order.
public class RecordComparator implements Comparator<Record>
{
@Override
public int compare(Record x, Record y)
{
// First compare times
int result = x.getTime().compareTo(y.getTime());
if(result != 0)
return result;
// Then somehow compare types...
}
}
You could define a
Map<Class, Integer>containing the sort orders for all the types, and then do this:Or something like that.
Keep in mind that it doesn’t have to be integers.