Elijah
Elijah

Reputation: 1322

java comparator on multidimensional array

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

Answers (3)

Egor
Egor

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

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Since both String and BigDecimal are Comparables:

return ((Comparable)o1).compareTo(o2);

Upvotes: 2

stacker
stacker

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

Related Questions