首頁 >Java >java教程 >java中Comparator和 Comparable的介紹及區別實例

java中Comparator和 Comparable的介紹及區別實例

零下一度
零下一度原創
2017-07-17 15:30:221892瀏覽

本文,先介紹Comparable 和Comparator兩個接口,以及它們的差異;接著,透過範例,對它們的使用方法進行說明。

Comparable 簡介

Comparable 是排序介面。

若一個類別實作了Comparable接口,就表示「該類別支援排序」。 即然實作Comparable介面的類別支援排序,假設現在存在“實作Comparable介面的類別的物件的List列表(或陣列)”,則該List列表(或陣列)可以透過Collections.sort(或Arrays.sort)進行排序。

此外,「實作Comparable介面的類別的物件」可以用作「有序映射(如TreeMap)」中的鍵或「有序集合(TreeSet)」中的元素,而不需要指定比較器。

1、Comparable的程式碼如下:

public interface Comparable<T> {public int compareTo(T o);
}

2、Comparator的程式碼如下

public interface Comparator<T> {int compare(T o1, T o2);boolean equals(Object obj);    // jdk1.8 后的方法default Comparator<T> reversed() {return Collections.reverseOrder(this);
    }default Comparator<T> thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);return (Comparator<T> & Serializable) (c1, c2) -> {int res = compare(c1, c2);return (res != 0) ? res : other.compare(c1, c2);
        };
    }default <U> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
    {return thenComparing(comparing(keyExtractor, keyComparator));
    }default <U extends Comparable<? super U>> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor)
    {return thenComparing(comparing(keyExtractor));
    }default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) {return thenComparing(comparingInt(keyExtractor));
    }default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) {return thenComparing(comparingLong(keyExtractor));
    }default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) {return thenComparing(comparingDouble(keyExtractor));
    }public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {return Collections.reverseOrder();
    }

    @SuppressWarnings("unchecked")public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
    }public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {return new Comparators.NullComparator<>(true, comparator);
    }public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {return new Comparators.NullComparator<>(false, comparator);
    }public static <T, U> Comparator<T> comparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
    {
        Objects.requireNonNull(keyExtractor);
        Objects.requireNonNull(keyComparator);return (Comparator<T> & Serializable)
            (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
                                              keyExtractor.apply(c2));
    }public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
            Function<? super T, ? extends U> keyExtractor)
    {
        Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable)
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
    }public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable)
            (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
    }public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable)
            (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));
    }public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable)
            (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2));
    }
}

Comparable和Comparator的主要差別在於:

  (1).Comparator 和Comparable都是Java中的內部比較器接口,都是用來實作對一個自訂的類別進行排序

#  (2). 不同的是實作Comparable介面是定義在類別的內部,比較程式碼需要嵌入類別的內部結構中

  (3 ).  Comparator 實作在類別的外部,單獨實作第一個比較器,不需要對原來的類別進行結構上的變化,屬於無侵入式的。

 

例如實作Comparable介面:

    class Score implements Comparable<Score>{  
      public int score;  
      public int time;  
        public int getScore() {  return score;  
    }  
      public void setScore(int score) {  this.score = score;  
    }  
      public int getTime() {  return time;  
    }  
      public void setTime(int time) {  this.time = time;  
    }  
      
        @Override  public int compareTo(Score o) {  if(this.time>o.time) return 1;  else if(this.time==o.time) return 0;  else return -1;  
        }  
      public Score(int score, int time) {  super();  this.score = score;  this.time = time;  
        }  
    }


實作Comparator介面的範例:

    class ScoreComparator implements Comparator<Score>{  
      
        @Override  public int compare(Score o1, Score o2) {  if(o1.time>o2.time) return 1;  else if(o1.time==o2.time) return 0;  else return -1;  
        }     
    }

然後呼叫ScoreComparator :

Arrays.sort(score, new ScoreComparator());

以上是java中Comparator和 Comparable的介紹及區別實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn