实现Comparable接口,把对象按优先级进行排序

在读《efficitive java》第12条:考虑实现Comparable接口

使用Comparable接口按对象按属性的优先级排序还是比较方便的
实例代码

package com.ctc.basic;

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

public class Student implements Comparable<Student> {

    private int number;

    private String name;

    private float score;

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

    //排序优先级number-name-score
    @Override
    public int compareTo(Student c) {
        // 如果number不等按number排序(增序
        if (this.number != c.number) {
            return this.number > c.number ? 1 : -1;
        } else {
            // 如果number和name都相等按score排序(降序)
            if (this.name.equals(c.name)) {
                return this.score < c.score ? 1 : -1;
            }
            // 如果number相等按name排序(增序)
            return this.name.compareTo(c.name) > 0 ? 1 : -1;
        }
    }

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

    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>() {
            {
                add(new Student(1, "a", 2));
                add(new Student(3, "a", 3));
                add(new Student(7, "a", 5));
                add(new Student(5, "a", 2));
                add(new Student(3, "a", 2));
                add(new Student(7, "c", 2));
                add(new Student(1, "b", 5));
                add(new Student(7, "a", 2));
                add(new Student(7, "c", 10));

            }
        };

        Collections.sort(students);
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

输出结果为

Student [number=1, name=a, score=2.0]
Student [number=1, name=b, score=5.0]
Student [number=3, name=a, score=3.0]
Student [number=3, name=a, score=2.0]
Student [number=5, name=a, score=2.0]
Student [number=7, name=a, score=5.0]
Student [number=7, name=a, score=2.0]
Student [number=7, name=c, score=10.0]
Student [number=7, name=c, score=2.0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tcoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值