首页 > 代码库 > 先按成绩由高到低,相等则按年龄由低到高

先按成绩由高到低,相等则按年龄由低到高

class Studentx implements Comparable<Studentx> {
    private String name;
    private int age;
    private float score;

    public Studentx(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String toString() {
        return "Studentx [name=" + name + ", age=" + age + ", score=" + score
                + "]";
    }

    public int compareTo(Studentx o) {
        if (this.score > o.score) {
            return -1;
        } else if (this.score < o.score) {
            return 1;
        } else {
            if (this.age > o.age) {
                return 1;
            } else {
                return 0;
            }
        }
    }

}

public class ComparableDemo01 {
    public static void main(String[] args) {
        Studentx studentx[] = { new Studentx("von", 20, 90.0f),
                new Studentx("korea", 24, 92.0f),
                new Studentx("susan", 18, 90.0f),
                new Studentx("lily", 30, 92.0f),
                new Studentx("boy", 28, 84.2f), new Studentx("cais", 23, 97.3f) };
        java.util.Arrays.sort(studentx);
        for (int i = 0; i < studentx.length; i++) {
            System.out.println(studentx[i]);
        }
    }
}