package com.ljs.day1; import java.util.Arrays; import java.util.Comparator; public class CompareDemo { public static void main(String[] args) { Student st1 = new Student(4, "ljs", 100); Student st2 = new Student(8, "it", 90); Student st3 = new Student(2, "que", 80); Student [] studens = new Student[] {st1,st2,st3}; Arrays.sort(studens,new CompareByGrade()); System.out.println(studens[0].toString()); System.out.println(studens[1].toString()); System.out.println(studens[2].toString()); } } class Student{ int id; String name; int grade; public Student(int id, String name, int grade){ this.id = id; this.name = name; this.grade = grade; } public String toString() { return "Student [id=" + id + ", name=" + name + ", grade=" + grade + "]"; } } class CompareById implements Comparator<Student>{ public int compare(Student o1, Student o2) { return o1.id - o2.id; } } class CompareByGrade implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { return o1.grade - o2.grade; } }