Java小demo-成绩排序

3 阅读1分钟
package com.stevenwong.package5;

import java.util.Objects;

public class Student implements Comparable<Student> {
    private String name;
    private int score;

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

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;
        return Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(name);
    }

    @Override
    public int compareTo(Student o) {
        return this.score - o.score;
    }
}
package com.stevenwong.package5;

import java.util.*;

public class ScoreDemo {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("aaa", 60));
        students.add(new Student("bbb", 10));
        students.add(new Student("ccc", 0));
        students.add(new Student("ddd", 90));
        students.add(new Student("eee", 100));
        students.add(new Student("eee", 100));

        // 去重
        Set<Student> set = new HashSet<>(students);
        System.out.println(set);

        // 排序
        Collections.sort(students);
        System.out.println(students);
    }
}
[Student{name='ccc', score=0}, Student{name='bbb', score=10}, Student{name='aaa', score=60}, Student{name='ddd', score=90}, Student{name='eee', score=100}]
[Student{name='ccc', score=0}, Student{name='bbb', score=10}, Student{name='aaa', score=60}, Student{name='ddd', score=90}, Student{name='eee', score=100}, Student{name='eee', score=100}]