利用Collections的reverseOrder方法:
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] arr = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(arr, Collections.reverseOrder());
for (Integer x : arr) {
System.out.print(x + " ");
}
System.out.println();
}
}
利用Comparator接口復寫compare方法:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
//注意,要想改變默認的排列順序,不能使用基本類型(int,double, char),而要使用它們對應的類
Integer[] arr = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
//定義一個自定義類MyComparator的對象
Comparator cmp = new MyComparator();
Arrays.sort(arr, cmp);
for (int x : arr) {
System.out.print(x + " ");
}
}
}
//實現Comparator接口
class MyComparator implements Comparator<Integer> {
@Override //作用是檢查下面的方法名是不是父類中所有的,也起到注釋的作用
public int compare(Integer a, Integer b) {
return a > b ? -1 : 1;
}
}