comparable和comparator

1概述

java中,对集合对象或者数组对象排序,有两种实现方式:

实现排序接口comparable

定义比较器comparator

下面用一个例子介绍上述两种实现方式

2实现comparable接口

我们先看一下Comparable的源码

public interface Comparable<T> {
  
    public int compareTo(T o);
}

就一个compareTo方法。

定义一个Student类并实现Comparable接口

public class Student implements Comparable<Student>{
    
    private String name;
    private int age;
    
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student s) {
        // TODO Auto-generated method stub
        return this.age-s.age;
    }
    
    public String toString(){
        return name+":"+age;
    }

}

该类实现Comparable接口的唯一方法compareTo,A.compareTo(B)返回值大于0时,表示A大于B,等于0表示A等于B,小于0表示A小于B。这里是通过student的age属性来进行比较。

然后新建一个测试类Test

public class Test {

    public static void main(String[] args) {
        
        List<Student> students = new ArrayList<>();
        students.add(new Student("ouym1",20));
        students.add(new Student("ouym2",22));
        students.add(new Student("ouym3",21));
        for(Student s : students){
            System.out.println(s.toString());
        }
        System.out.println("---------------sort--------------");
        Collections.sort(students);
        for(Student s : students){
            System.out.println(s.toString());
        }
        

    }

}

先向List中添加三个Student对象,然后按ArrayList的顺序输出(添加顺序),接下来调用Collections.sort(students)排序,我们看一下排序后的List。

ouym1:20
ouym2:22
ouym3:21
---------------sort--------------
ouym1:20
ouym3:21
ouym2:22

按照age升序。若想要降序只需要将compareTo中的this.age-s.age变为s.age-this.age即可。

3定义比较器comparator

还是上面那个例子,Student类添加get和set方法,接下来我们定义一个comparator的实现类

public class MyComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        return o1.getName().compareTo(o2.getName());
    }

}

下面是测试类Test

public class Test {

    public static void main(String[] args) {
        
        List<Student> students = new ArrayList<>();
        students.add(new Student("ouym1",20));
        students.add(new Student("ouym3",22));
        students.add(new Student("ouym2",21));
        
        Collections.sort(students,new MyComparator());
        for(Student s : students){
            System.out.println(s.toString());
        }
        
    }

}

输出

ouym1:20
ouym2:21
ouym3:22

MyComparator比较器按照name升序排列。

猜你喜欢

转载自www.cnblogs.com/ouym/p/9037569.html
今日推荐