Java Comparable接口介绍和使用

883 阅读2分钟

Comparable源码介绍

jdk版本:1.8.0

public interface Comparable<T> {
    /**
     * Compares this object with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     */
    public int compareTo(T o);
}

Comparable接口定义了 compareTo函数,其函数会比较两个Object,并返回正整数、零、负整数。

当某个类对象需要进行比较、排序时,需要实现Comparable接口。

通过List<Integer>的比较理解Comparable接口

Integer类实现Comparable接口,因此可以使用Collections.sort()方法进行排序。

Integer类实现Comparable接口类的提纯源代码如下:(jdk版本:1.8.0)

public final class Integer extends Number implements Comparable<Integer> {
    public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }

    public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
}

List<Integer>排序代码如下

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<>(4);
        intList.add(54);
        intList.add(12);
        intList.add(43);
        intList.add(9);
        Collections.sort(intList);
        System.out.printf("排序后的int List: %s \n",intList); //排序后的int List: [9, 12, 43, 54]
    }
}

自定义类实践过程

创建一个未实现Comparable接口类的People类:

class People{
    private String name;
    private int age;

    People(String name,int age){
        this.name = name;
        this.age = age;
    }
}

创建People类List,并添加四个人:

List<People> list = new ArrayList<>(4);
list.add(new People("a",19));
list.add(new People("c",10));
list.add(new People("b",45));
list.add(new People("d",16));

直接对list通过Collections.sort排序,会报错:因为没有实现Comparable接口类。

image.png

修改People类如下:实现按照age降序排序,age相同时,按照name升序排序

class People implements Comparable<People>{
    private String name;
    private int age;

    People(String name,int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(People o) {
        if (this.age != o.age){
            return o.age-this.age; // 按照age降序排序
        }
        return this.name.compareTo(o.name); // age相同,按照name降序排序
    }

    @Override
    public String toString(){
        return this.name+"_"+this.age;
    }
}

排序实现:

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

public class Main {
    public static void main(String[] args) {
        List<People> list = new ArrayList<>(6);
        list.add(new People("a",19));
        list.add(new People("c",16));
        list.add(new People("e",45));
        list.add(new People("d",16));
        list.add(new People("b",45));
        list.add(new People("f",8));
        Collections.sort(list);
        System.out.println("排序后的list:");
        for (People e:list){
            System.out.println(e.toString());
        }
    }
}

输出结果:

排序后的list:
b_45
e_45
a_19
c_16
d_16
f_8