rmaik
rmaik

Reputation: 1086

how to make a generic comparator method

i have a utility class and i want to have a generic method for sorting so that, and arrayList of any type passed to this static method posted below, the will be sorted.

when i write the below code, eclipse asks to add the unimplemented methods, and when i accept adding them , i found that they are too many and i do not know which one should i use

CODE:

public static <T> void sortAsc(ArrayList<T> list) {
    Collections.sort(list, ascOrder);
}

private static Comparator<T> ascOrder = new Comparator<T>() {

    public int compare(DMatch arg0, DMatch arg1) {
        // TODO Auto-generated method stub

        return Float.compare(arg0.distance, arg1.distance);
    }
};

Upvotes: 0

Views: 420

Answers (3)

candied_orange
candied_orange

Reputation: 7344

To do what you're trying to do you need a type that ensures there will be a getDistance() method. That can be an abstract class or an interface. Whichever it is I'm calling it HasDistance.

public static void sortAsc(ArrayList<? extends HasDistance> list) {
    Collections.sort(list, ascOrder);
}

private static Comparator<HasDistance> ascOrder = new Comparator<>() {

    public int compare(HasDistance arg0, HasDistance arg1) {
        return Float.compare(arg0.getDistance(), arg1.getDistance());
    }
};

Upvotes: 1

Lucas Levi
Lucas Levi

Reputation: 21

After Java 8 you can just use yourList.sort(param). The method param can be a Comparator or null if the items in your list implements Comparable interface.

Upvotes: 0

rossum
rossum

Reputation: 15693

If you want to sort "any type" then you will need to pick something that will work with "any type". Essentially, you want to sort a list of Object. That will probably limit you to comparing myObject.hashCode() or myObject.toString(). Pick one or the other and stick with it consistently. Whether or not the ordering you get from either of these methods will be useful is a completely different question.

If you can make the contents of your list less general, then you will have a wider range of options to sort on.

Upvotes: 0

Related Questions