collections.sort 中物件 o1,o2 的含義是什么?以及為什么他不寫 Process 而不是 object 因為我們的串列基于 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;
}
});
}
uj5u.com熱心網友回復:
當您轉向sort方法的 javadoc 時,您會發現它接受Comparator<? super T> c作為引數。
Object是一個超型別,Process因此給定的例子是正確的java代碼。
現在:根據您的要求,可能有實際使用超型別的正當理由,但不是在這里:給定的示例實際上可以Process直接使用,這將允許在 lambda 的主體內洗掉型別轉換。
uj5u.com熱心網友回復:
(Object o1, Object o2)參考Comparator::compareTo方法的引數,但是,Process應該使用型別而不是物件以避免冗余轉換。
此外,根據 的型別Process::getRemaningTime,方法的主體可能會顯著減少。
假設getRemaningTime回傳一個長值,代碼可以改寫為:
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));
}
在一般情況下,回傳的值getRemaningTime應該是Comparable型別,然后該方法可以更新為使用Comparator.comparing(Function<? super T,? extends U> keyExtractor):
public static void sortRemaning(List<Process> list) {
Collections.sort(list, Comparator.comparing(Process::getRemaningTime));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/384543.html
