Discuss / Java / 练习:按score从高到低排序

练习:按score从高到低排序

Topic source

韦雪松

#1 Created at ... [Delete] [Delete and Lock User]
import java.util.Arrays;

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

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Person other) {
        return other.score - this.score;
    }
}

public class Main {
    public static void main(String[] args) {
        Person[] p = new Person[]{
                new Person("Bob", 61),
                new Person("Alice", 88),
                new Person("Lily", 75)
        };
        Arrays.sort(p);
        System.out.println(Arrays.toString(p));
    }
}

  • 1

Reply