4.9 深入理解Arrays.sort(T[],Comparator<? super T>c)

Arrays.sort(T[],Comparator<? super T>c)是一種用于對(duì)用戶定義的對(duì)象數(shù)組進(jìn)行排序的方法。官方的Java Doc 簡(jiǎn)單地描述它做了什么,但不是深入立即。在這篇文章中,我將介紹關(guān)鍵信息,以便更深入地介紹這種方法。

1.如何用Arrays.sort():一個(gè)簡(jiǎn)單例子

通過閱讀下面的例子,你可以對(duì)如何使用這個(gè)方法有個(gè)正確的認(rèn)識(shí)。定義一個(gè)比較器,用于按照狗的尺寸來比較大小,然后比較器用排序方法的參數(shù)。

import java.util.Arrays;
import java.util.Comparator;
 
class Dog{
    int size;   
    public Dog(int s){
        size = s;
    }
}
 
class DogSizeComparator implements Comparator<Dog>{
 
    @Override
    public int compare(Dog o1, Dog o2) {
        return o1.size - o2.size;
    }
}
 
public class ArraySort {
 
    public static void main(String[] args) {
        Dog d1 = new Dog(2);
        Dog d2 = new Dog(1);
        Dog d3 = new Dog(3);
 
        Dog[] dogArray = {d1, d2, d3};
        printDogs(dogArray);
 
        Arrays.sort(dogArray, new DogSizeComparator()); 
        printDogs(dogArray);
    }
 
    public static void printDogs(Dog[] dogs){
        for(Dog d: dogs)
            System.out.print(d.size + " " );
 
        System.out.println();
    }
}

輸出:

2 1 3
1 2 3

2.Arrays.sort()中使用的策略模式

這是一個(gè)很好使用策略模式的例子,值得注意的是為什么策略模式在這里會(huì)比較適合。簡(jiǎn)而言之,策略模式準(zhǔn)許在運(yùn)行時(shí)候選擇不同的算法。在這種情況下,通過傳遞不同的比較器,可以選擇不同的算法?;谏厦娴睦?,假若你有另外一個(gè)比較器,比較狗的重量而不是大小,你可以簡(jiǎn)單地創(chuàng)建一個(gè)新的比較器,如下:

class Dog{
    int size;
    int weight;
 
    public Dog(int s, int w){
        size = s;
        weight = w; 
    }
}
 
class DogSizeComparator implements Comparator<Dog>{
 
    @Override
    public int compare(Dog o1, Dog o2) {
        return o1.size - o2.size;
    }
}
 
class DogWeightComparator implements Comparator<Dog>{
 
    @Override
    public int compare(Dog o1, Dog o2) {
        return o1.weight - o2.weight;
    }
}
 
public class ArraySort {
 
    public static void main(String[] args) {
        Dog d1 = new Dog(2, 50);
        Dog d2 = new Dog(1, 30);
        Dog d3 = new Dog(3, 40);
 
        Dog[] dogArray = {d1, d2, d3};
        printDogs(dogArray);
 
        Arrays.sort(dogArray, new DogSizeComparator()); 
        printDogs(dogArray);
 
        Arrays.sort(dogArray, new DogWeightComparator());   
        printDogs(dogArray);
    }
 
    public static void printDogs(Dog[] dogs){
        for(Dog d: dogs)
            System.out.print("size="+d.size + " weight=" + d.weight + " ");
 
        System.out.println();
    }
}
size=2 weight=50 size=1 weight=30 size=3 weight=40 
size=1 weight=30 size=2 weight=50 size=3 weight=40 
size=1 weight=30 size=3 weight=40 size=2 weight=50 

Comparator 僅僅是個(gè)接口,任何實(shí)現(xiàn)這個(gè)接口的比較器都可以在運(yùn)行時(shí)候被使用。這是策略模式的關(guān)鍵思想。

3.為什么用"Super"

如果直接用Comparator<T> c 作為參數(shù),第二個(gè)參數(shù)是"Comparator<? super T> c" <? super T>意味這類型可以是T或者它的父類型。為什么準(zhǔn)許父類型。答案是:
這種方法準(zhǔn)許為所有的子類使用相同的比較器。以下的示例是明顯的:

import java.util.Arrays;
import java.util.Comparator;
 
class Animal{
    int size;
}
 
class Dog extends Animal{
    public Dog(int s){
        size = s;
    }
}
 
class Cat extends Animal{
    public Cat(int s){
        size  = s;
    }
}
 
class AnimalSizeComparator implements Comparator<Animal>{
 
    @Override
    public int compare(Animal o1, Animal o2) {
        return o1.size - o2.size;
    }
    //in this way, all sub classes of Animal can use this comparator.
}
 
public class ArraySort {
 
    public static void main(String[] args) {
        Dog d1 = new Dog(2);
        Dog d2 = new Dog(1);
        Dog d3 = new Dog(3);
 
        Dog[] dogArray = {d1, d2, d3};
        printDogs(dogArray);
 
        Arrays.sort(dogArray, new AnimalSizeComparator());  
        printDogs(dogArray);
 
        System.out.println();
 
        //when you have an array of Cat, same Comparator can be used. 
        Cat c1 = new Cat(2);
        Cat c2 = new Cat(1);
        Cat c3 = new Cat(3);
 
        Cat[] catArray = {c1, c2, c3};
        printDogs(catArray);
 
        Arrays.sort(catArray, new AnimalSizeComparator());  
        printDogs(catArray);
    }
 
    public static void printDogs(Animal[] animals){
        for(Animal a: animals)
            System.out.print("size="+a.size + " ");
        System.out.println();
    }
}
size=2 size=1 size=3 
size=1 size=2 size=3 

size=2 size=1 size=3 
size=1 size=2 size=3 

4.總結(jié)

1、用通用父類。
2、策略模式。
3、合并排序-nlog(n)時(shí)間復(fù)雜度。
4、Java.util.Collections.sort(List <T> list,Comparator <?super T> c)與Arrays.sort有類似的思想。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,728評(píng)論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • Arrays.sort(T[], Comparator < ? super T > c) 是用來對(duì)用戶自定義的對(duì)象...
    汪梓文閱讀 217評(píng)論 0 0
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,810評(píng)論 11 349
  • 一、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對(duì)于byte類型而言...
    龍貓小爺閱讀 4,455評(píng)論 0 16

友情鏈接更多精彩內(nèi)容