版本1
外置重载比较器类
import java.util.*; public class perfomanceSort { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { int n = in.nextInt(); String s; int age, score; Student stu[]= new Student[n]; for( int i = 0; i < n; i++) { s = in.next(); age = in.nextInt(); score = in.nextInt(); stu[i] = new Student(s, age, score); } Arrays.sort(stu, new cmp()); for(int i = 0; i < n; i++) { System.out.println(stu[i].name+" "+stu[i].age+" "+stu[i].score); } } } public static class Student{ public int age; public int score; public String name; Student(String name, int age, int score){ this.age = age; this.name = name; this.score = score; } } public static class cmp implements Comparator<Student>{ public int compare(Student s1, Student s2) { if(s1.score != s2.score) return s1.score < s2.score ? -1: 1; else if(s1.name.compareTo(s2.name) != 0) return s1.name.compareTo(s2.name) < 0 ? -1: 1; return s1.age < s2.age ? -1: 1; } } }
版本2
内置比较器
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class second { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { int n = in.nextInt(); Student stu[] = new Student[n]; for( int i = 0; i < n; i++) { stu[i]=new Student(in.next(), in.nextInt(), in.nextInt()); } Arrays.sort(stu, new Comparator<Student>() { public int compare(Student o1, Student o2) { if(o1.score == o2.score){ if(o1.name.compareTo(o2.name) == 0){ return o1.age - o2.age; } return o1.name.compareTo(o2.name); } return o1.score - o2.score; } }); for(int i = 0; i < n; i++) { System.out.println(stu[i].name+" "+stu[i].age+" "+stu[i].score); } } } public static class Student{ int age; int score; String name; Student(String name, int age, int score){ this.age = age; this.name = name; this.score = score; } } }
版本3
2021.04.03
主要考点:数组排序,重写Comparator方法
import java.util.*; public class Main{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String name; int age, score; List<Stu> list = new ArrayList(); for(int i = 0; i < n; i++){ name = in.next(); age = in.nextInt(); score = in.nextInt(); list.add(new Stu(name, age,score)); } // 排序 Collections.sort(list, (o1, o2) -> { if(o1.score != o2.score) return o1.score - o2.score; else if(!o1.name.equals(o2.name)) return o1.name.compareTo(o2.name); else return o1.age - o2.age; }); // 输出 for(Stu s: list){ System.out.println(s.name+" "+s.age +" "+s.score); } } public static class Stu{ String name; int age; int score; public Stu(String name, int age, int score) { this.name = name; this.age = age; this.score = score; } } }