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