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;}

    }
}

  • 1

Reply