Home > Net >  what is the meaning of object here in collections.sort?
what is the meaning of object here in collections.sort?

Time:12-14

what is the meaning of object o1,o2 here in collections.sort? and why he didn't write Process instead of object beacuse our list is based on process object

public static void sortremaning(ArrayList<Process> L) {
    Collections.sort(L, (Object o1, Object o2) -> {
        if (((Process) o1).getRemaningtime() == ((Process) o2).getRemaningtime()) {
            return 0;
        } else if (((Process) o1).getRemaningtime() < ((Process) o2).getRemaningtime()) {
            return -1;
        } else {
            return 1;
        }
    });
}

CodePudding user response:

When you turn to the javadoc for the sort method you find that it accepts Comparator<? super T> c as argument.

Object is a supertype of Process therefore the given example is correct java code.

Now: depending on your requirements, there might be a valid reason to actually work with a supertype, but not here: the given example could in fact use Process directly, which would allow to drop the type casts within the body of the lambda.

CodePudding user response:

(Object o1, Object o2) refer to the arguments of Comparator::compareTo method, however, Process type should be used instead of Object to avoid redundant casting.

Also, depending on the type of Process::getRemaningTime, the body of the method may be reduced significantly.

Assuming getRemaningTime returns a long value, the code may be rewritten as:

public static void sortremaning(ArrayList<Process> L) {
    Collections.sort(L, (p1, p2) -> Long.compareTo(p1.getRemaningTime(), p2.getRemaningTime()));
}

// or even simpler
public static void sortRemaning(ArrayList<Process> L) {
    Collections.sort(L, Comparator.comparingLong(Process::getRemaningTime));
}

In general case, the value returned by getRemaningTime should be of Comparable type, then the method can be updated as to use Comparator.comparing(Function<? super T,? extends U> keyExtractor):

public static void sortRemaning(List<Process> list) {
    Collections.sort(list, Comparator.comparing(Process::getRemaningTime));
}
  • Related