Comparable接口实现自定义对象的排序功能

有时需要通过比较对象的某个值来将对象的数组进行排序,
可以通过自定义方法来实现,
但是使用comparable接口会很方便的实现不同属性的比较排序.
写一个Student类

// 泛型写什么  就是和什么比较
public class Student implements Comparable<Student>{

    private String name;

    private int score;

    public static boolean desc; // true 降序  false 升序
    // 排序方式对所有对象都是保持一致 ,使用static来保持一致
    // 并且也直接使用类名调用比较简单 

    // 所有对象独享的,定义为静态变量
    // 每个对象独享的,定义为普通变量

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Student(String name, int score) {
        super();
        this.name = name;
        this.score = score;
    }

    public int compareTo(Student o) {
        // 比较的结果返回值如下所示
        // 负数  0  正数
        // 负数 tihs < o
        // 0 this == o
        // 正数 this > o

//      if (this.score < o.score) {
//          return -1;
//      }
//      if (this.score == o.score) {
//          return 0;
//      }
//      if (this.score > o.score) {
//          return 1;
//      }

        // 这是一种更简便的写法
        // 降序
        if (Student.desc) {
            return o.score - this.score;
        }else {
            // 升序
            return this.score - o.score;            
        }

        // 当然还有更简便的写法
        return (this.score - o.score) * (Student.desc ? -1 : 1);
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", score=" + score + "]";
    }


}

在创建一个Test类进行使用

public class Test {

    public static void main(String[] args) {

        Student s1 = new Student("张三",90);
        Student s2 = new Student("李四",75);
        Student s3 = new Student("王五",80);
        Student s4 = new Student("马六",60);
        Student s5 = new Student("田七",83);
        Student s6 = new Student("赵八",71);

        ArrayList<Student> al1 = new ArrayList<Student>();

        al1.add(s1);
        al1.add(s2);
        al1.add(s3);
        al1.add(s4);
        al1.add(s5);
        al1.add(s6);

        // 使用desc来选择升降序排列
        Student.desc = true;
        Collections.sort(al1);

        for (Student student : al1) {

            System.out.println(student);
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值