comparable接口

时光怂恿深爱的人放手 提交于 2020-01-19 14:21:03

要相对我们自定义的类使用Collections类里面的sort方法进行排序,必须实现comparable接口规定排序规则

要实现public int compareTo(T o)方法

使用如下

import java.util.ArrayList;
import java.util.Collections;
 
class Student implements Comparable{
    private String name;
    private int ranking;
 
    public Student(String name, int ranking){
        this.name = name;
        this.ranking = ranking;
    } 
 
    public String toString(){
        return this.name + ":" + this.ranking;
    }
 
    public int compareTo(Object o){
        Student s = (Student)(o);
        return this.ranking - s.ranking;
    }
}
 
public class Compare2{
    public static void f(){
        ArrayList arr = new ArrayList();
        arr.add(new Student("Jack",10));
        arr.add(new Student("Bill",23));
        arr.add(new Student("Rudy",7));
 
        System.out.println(arr);
        Collections.sort(arr);
        System.out.println(arr);
    } 
}

Collections.sort()默认是升序排序的,但是如果我们想降序排序,可以使用

Collections.sort(list,Collections.reverseOrder());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!