题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); ArrayList<Student> list = new ArrayList<>(); int type = sc.nextInt(); for (int i = 0; i < num; i++) { String name = sc.next(); int score = sc.nextInt(); list.add(new Student(name, score)); } Comparator<Student> comparator = type == 1 ? new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Student) o1).score - ((Student) o2).score; } } : new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Student) o2).score - ((Student) o1).score; } }; list.sort(comparator); for (Student student : list) { System.out.println(student.name + " " + student.score); } } } class Student { String name; Integer score; public Student() { } public Student(String name, Integer score) { this.name = name; this.score = score; } }
成员变量最好还是私有化