Introduction 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!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor