search
HomeJavajavaTutorialIntroduction and difference examples of Comparator and Comparable in java

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);
}</t>

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>> 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>> Comparator<t> reverseOrder() {return Collections.reverseOrder();
    }

    @SuppressWarnings("unchecked")public static <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> 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>> 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));
    }
}</t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></u></t></u></t></t></t></t>

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;  
        }  
    }</score>


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;  
        }     
    }</score>

Then call ScoreComparator:

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

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!

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use