search
HomeJavajavaTutorialComparison and use of Comparable and Comparator

Comparison and use of Comparable and Comparator

Jul 24, 2017 am 10:19 AM
comparablecomparator

Overview

1. Background on the use of Comparable and Comparator

Numeric data (byte int short long float double) It is naturally comparable in size and sortable. String implements the Comparable interface and can also compare sizes and sort. However, there are many kinds of custom classes, and there is no common indicator that can be used as a sorting indicator. Therefore, it is necessary to manually establish comparisons in the custom class. Method, for this purpose, java provides two interfaces Comparable and Comparator.

2. Collection sorting

Collections.sort() underlying sorting relies on Arrays.sort(), and Arrays.sort() The bubble method is used for sorting.

二Comparable

Objects that need to be compared in size can implement the Comparable interface and implement the abstract method in it, which is used to set the comparison The way. The following is an example to illustrate:

1. Entity class

package com.javase.collections.comparable;public class Student implements Comparable<student> {private String name;private int score;public Student() {super();
    }public Student(String name, int score) {super();this.name = name;this.score = score;
    }public String getName() {return name;
    }public void setName(String name) {this.name = name;
    }public int getScore() {return score;
    }public void setScore(int score) {this.score = score;
    }

    @Overridepublic int compareTo(Student stu) {return this.score - stu.score;// 操作对象减去参数对象,升序排列,反之降序。    }

}</student>

In the compareTo() method, use The attribute score is the sorting indicator, using "this.score-stu.score". The final results are arranged in ascending order, and vice versa.

2. Test class

package com.javase.collections.comparable;import java.util.ArrayList;import java.util.Collections;import java.util.List;import org.junit.Test;public class ComparableTest {

    @Testpublic void testComparable() {
        List<student> stus = new ArrayList<student>();
        Student zhangsan = new Student("zhangsan", 100);
        Student lisi = new Student("lisi", 90);
        Student wanger = new Student("wanger", 95);
        stus.add(zhangsan);
        stus.add(lisi);
        stus.add(wanger);
        System.out.println("排序前");for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
        System.out.println("排序后");
        Collections.sort(stus);for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
    }

}</student></student>

Output:

三Comparator

If a class does not implement the Comparable interface when it is created, you want to object to it without modifying the source code To sort, you can implement the Comparator interface and specify the sorting method when calling the sorting method. The following is an example to illustrate:

1. Entity class

package com.javase.collections.comparator;public class Student {private String name;private int score;public Student() {super();
    }public Student(String name, int score) {super();this.name = name;this.score = score;
    }public String getName() {return name;
    }public void setName(String name) {this.name = name;
    }public int getScore() {return score;
    }public void setScore(int score) {this.score = score;
    }

}

2. Test class

package com.javase.collections.comparator;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import org.junit.Test;public class ComparatorTest {

    @Testpublic void test() {
        List<student> stus = new ArrayList<student>();
        Student zhangsan = new Student("zhangsan", 100);
        Student lisi = new Student("lisi", 90);
        Student wanger = new Student("wanger", 95);
        stus.add(zhangsan);
        stus.add(lisi);
        stus.add(wanger);
        System.out.println("排序前");for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
        System.out.println("-----------------------");
        Collections.sort(stus, new Comparator<student>() {
            @Overridepublic int compare(Student stu01, Student stu02) {// return stu01.getScore() - stu02.getScore();//升序return stu02.getScore() - stu01.getScore();// 降序            }
        });

        System.out.println("排序后");for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
    }

}</student></student></student>

In the compare(Student stu01, Student stu02) method, the attribute score is used as the sorting indicator, using "stu01.score-stu02.score", and the final results are arranged in ascending order. Vice versa in descending order.

Output:

##

The above is the detailed content of Comparison and use of Comparable and Comparator. 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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment