Reputation: 1322
Is there a better way to write this comparator? I have an equivalent of multidimensional array where columns are Object
's. The actual objects are String
and BigDecimal
99% of the time. I am sorting "rows" on a given column index.
I want to avoid instanceof.
protected static class MyComparator implements Comparator<DataRow> {
private int idx;
public MyComparator(int idx) {
this.idx = idx;
}
@Override
public int compare(DataRow r1, DataRow r2) {
Object o1 = r1.getColumns()[idx];
Object o2 = r2.getColumns()[idx];
if (o1 instanceof String){
return ((String)o1).compareTo((String)o2);
}else if (o1 instanceof BigDecimal){
return ((BigDecimal)o1).compareTo((BigDecimal)o2);
}else{
throw new UnsupportedOperationException("comparison cannot be performed");
}
}
Upvotes: 2
Views: 344
Reputation: 181
If the colum types are not comparable, I would implement separate comparators and make the Column class a factory for the correct comparator that should be used.
Upvotes: 0
Reputation: 51030
Since both String
and BigDecimal
are Comparable
s:
return ((Comparable)o1).compareTo(o2);
Upvotes: 2
Reputation: 68942
I think since you only depend on the type Comparable you could rewrite it as:
public int compare(DataRow r1, DataRow r2) {
Comparable o1 = (Comparable) r1.getColumns()[idx];
Comparable o2 = (Comparable) r2.getColumns()[idx];
return o1.compareTo(o2);
}
If you carefully populate the table you shouldn't face the UnsupportedOperationException situation.
Upvotes: 1