Discuss / Java / 按成绩排序

按成绩排序

Topic source

CSU孔文佳

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {
    public static void main(String[] args) throws Exception {
        Person[] ps = new Person[] {
                new Person("Bob", 61),
                new Person("Alice", 88),
                new Person("Lily", 75),
        };
        Arrays.sort(ps);
        System.out.println(Arrays.toString(ps));

    }
}

class Person implements Comparable<Person> {
    String name;
    int age;

    Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return this.name + "," + this.age;
    }
    @Override    public int compareTo(Person other) {
        if (this.age > other.age){return 1;}
        else if (this.age > other.age){return -1;}
        else{return 0;}

    }
}

pineapple_py

#2 Created at ... [Delete] [Delete and Lock User]

成绩的排序,用三元运算符更简单

    @Override public int compareTo(Person other) {
        return this.score > other.score ? 0 : 1;
    }

为什么 要多此一举呢?


  • 1

Reply