How to handle sorting of complex objects?

Posted by AedonEtLIRA on Programmers See other posts from Programmers or by AedonEtLIRA
Published on 2012-12-06T22:03:19Z Indexed on 2012/12/06 23:24 UTC
Read the original article Hit count: 244

Filed under:
|
|

How would one sort a list of objects that have more than one sortable element?

Suppose you have a simple object Car and car is a defined as such:

class Car {
    public String make;
    public String model;
    public int year;
    public String color;
    // ... No methods, just a structure / container
}

I designed a simple framework that would allow for multiple SortOptions to be provided to a Sorter that would then sort the list.

interface ISorter<T> {
    List<T> sort(List<T> items);
    void addSortOption(ISortOption<T> option);
    ISortOption<T>[] getSortOptions();
    void setSortOption(ISortOption<T> option);
}

interface ISortOption<T> {
    String getLabel();
    int compare(T t1, T t2);
}

Example use

class SimpleStringSorter extends MergeSorter<String> {
    {
        addSorter(new AlphaSorter());
    }

    private static final class AlphaSorter implements ISortOption<String> {
        // ... implementation of alpha compare and get label
    }
}

The issue with this solution is that it is not easily expandable. If car was to ever receive a new field, say, currentOwner. I would need to add the field, then track down the sorter class file, implement a new sort option class then recompile the application for redistribution.

Is there an easier more expandable/practical way to sort data like this?

© Programmers or respective owner

Related posts about java

Related posts about design-patterns