Home > Java > javaTutorial > body text

Introduction and difference examples of Comparator and Comparable in java

零下一度
Release: 2017-07-17 15:30:22
Original
1814 people have browsed it

This article first introduces the two interfaces Comparable and Comparator and their differences; then, uses examples to explain their use.

Comparable Introduction

Comparable is a sorting interface.

If a class implements the Comparable interface, it means "this class supports sorting". Since the class that implements the Comparable interface supports sorting, assuming that there is now a "List (or array) of objects of the class that implements the Comparable interface", the List (or array) can be processed through Collections.sort (or Arrays.sort) Sort.

In addition, "objects of classes that implement the Comparable interface" can be used as keys in "ordered maps (such as TreeMap)" or elements in "ordered sets (TreeSet)" without specifying comparisons. device.

1. The code of Comparable is as follows:

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

2. The code of Comparator is as follows

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));
    }
}
Copy after login

The main features of Comparable and Comparator The difference is:

 (1).Comparator and Comparable are both internal comparator interfaces in Java, and are used to sort a custom class

 (2). The difference is that the implementation of the Comparable interface is defined inside the class, and the comparison code needs to be embedded in the internal structure of the class

 (3 ). Comparator is implemented outside the class, and the first comparator is implemented separately. There is no need to make structural changes to the original class, and it is non-intrusive.

For example, implement the Comparable interface:

    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;  
        }  
    }
Copy after login


Example of implementing the Comparator interface:

    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;  
        }     
    }
Copy after login

Then call ScoreComparator:

Arrays.sort(score, new ScoreComparator());
Copy after login

The above is the detailed content of Introduction and difference examples of Comparator and Comparable in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!