1. 程式人生 > 其它 >Comparable和Comparator的比較與使用

Comparable和Comparator的比較與使用

技術標籤:Javalambdajdk面向物件程式設計java後端

Comparable與Comparator的使用

從字面意思我們就可以看出,Comparable是具有比較能力的,Comparator是比較器,那麼前者很顯然是指某個物件具有比較能力的,就好像是一種技能,而後者是給一個比較的工具,我們使用這個工具來進行比較。

Comparable

Comparable介面中只有一個方法:

public interface Comparable<T> {
    // 返回值:
    // < 0: 表示 this 指向的物件小於 o 指向的物件
    // == 0: 表示 this 指向的物件等於 o 指向的物件
// > 0: 表示 this 指向的物件等於 o 指向的物件 public int compareTo(T o); }

在java中的很多類都實現了這個介面,比方說Integer、Long等包裝類,String類等等。

例項:某個班有若干學生,現需要進行按身高進行排隊(從小到大)。

分析:需要一個學生類,學生類需要具備比較能力(Comparable),所以其內部必須實現compareTo方法。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class
Student implements Comparable<Student>{ private String name;//姓名 private int hight;//身高 public Student(String name, int hight) { this.name = name; this.hight = hight; } public String getName() { return name; } public void setName(String name)
{ this.name = name; } public double getHight() { return hight; } public void setHight(int hight) { this.hight = hight; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", hight=" + hight + '}'; } @Override public int compareTo(Student stu) { if(this.hight == stu.hight){ return 0; }else if(this.hight > stu.hight){ return 1; }else{ return -1; } } public static void main(String[] args) { List<Student> stus = new ArrayList<>(); Student stu1 = new Student("張三",177); Student stu2 = new Student("李四",160); Student stu3 = new Student("王五",182); Student stu4 = new Student("趙六",165); stus.add(stu1); stus.add(stu2); stus.add(stu3); stus.add(stu4); Collections.sort(stus); for(Student s : stus){ System.out.println(s); } } }

執行結果:

在這裡插入圖片描述

Comparator

Comparator中根據JDK版本不同,其方法的數量不同,但是值得注意的是,它是一個函式式介面,所以可以使用lambda表示式。

@FunctionalInterface
public interface Comparator<T> {
    // 返回值:
    // < 0: 表示 this 指向的物件小於 o 指向的物件
    // == 0: 表示 this 指向的物件等於 o 指向的物件
    // > 0: 表示 this 指向的物件等於 o 指向的物件
    int compare(T o1, T o2);
    boolean equals(Object obj);
}

@FunctionalInterface該註解表示函式式介面,介面內除object的public方法外,只有一個抽象方法。

例項:公司有若干員工,需要對其工資進行排序(從大到小)

分析:需要員工類,在員工集合中對其進行排序,傳入比較器,這裡直接匿名實現。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Employee {
    private String name;//員工姓名
    private int Salary;//月工資

    public Employee(String name, int salary) {
        this.name = name;
        this.Salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return Salary;
    }

    public void setSalary(int salary) {
        Salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", Salary=" + Salary +
                '}';
    }

    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>();
        Employee emp1 = new Employee("張三",5000);
        Employee emp2 = new Employee("李四",6000);
        Employee emp3 = new Employee("王五",4500);
        Employee emp4 = new Employee("趙六",8000);

        list.add(emp1);
        list.add(emp2);
        list.add(emp3);
        list.add(emp4);

        Collections.sort(list, new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                if(o1.Salary == o2.Salary){
                    return 0;
                }else if(o1.Salary > o2.Salary){
                    return -1;
                }else{
                    return 1;
                }
            }
        });
        for(Employee e:list){
            System.out.println(e);
        }
    }
}

執行結果:

在這裡插入圖片描述

使用lambda表示式:

//使用lambda表示式
        Collections.sort(list,(o1,o2)->{
            if(o1.Salary == o2.Salary){
                return 0;
            }else if(o1.Salary > o2.Salary){
                return -1;
            }else{
                return 1;
            }
        });

因為比較的本身就是int,可以利用compare的返回值特性使其變得更簡化。上面Comparable也是如此。

    //使用lambda表示式,並利用compare返回值特性更簡化。
    Collections.sort(list,((o1, o2) -> (o2.Salary - o1.Salary)));