简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM