/**
* @auther atton;
* @create 2022-10-17-下午 1:56;
*/
public class Bijiaoqi {
//学生类
public static class Student{
public String name;
public int id;
public int age;
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
Student s1 = new Student("A", 2, 20);
Student s2 = new Student("B", 3, 21);
Student s3 = new Student("C", 1, 23);
Student s4 = new Student("D", 0, 22);
Student s5 = new Student("D", 4, 22);
Student s6 = new Student("D", 5, 22);
Student[] stu = new Student[]{s1, s2, s3, s4,s5,s6};
for(Student s : stu){
System.out.println(s);
}
/*输出
Student{name='A', id=2, age=20}
Student{name='B', id=3, age=21}
Student{name='C', id=1, age=23}
Student{name='D', id=0, age=22}
Student{name='D', id=4, age=22}
Student{name='D', id=5, age=22}
*/
//id升序排序后的学生
Arrays.sort(stu,new IdAscend());
System.out.println("id升序排序后的");
for(Student s : stu){
System.out.println(s);
}
/*id升序排序后的
Student{name='D', id=0, age=22}
Student{name='C', id=1, age=23}
Student{name='A', id=2, age=20}
Student{name='B', id=3, age=21}
Student{name='D', id=4, age=22}
Student{name='D', id=5, age=22}
*/
//年龄和id升序排序后的学生
Arrays.sort(stu, new AgeIdAsecnd());
System.out.println("年龄和id升序");
for(Student s : stu){
System.out.println(s);
}
/*年龄和id升序
Student{name='A', id=2, age=20}
Student{name='B', id=3, age=21}
Student{name='D', id=0, age=22}
Student{name='D', id=4, age=22}
Student{name='D', id=5, age=22}
Student{name='C', id=1, age=23}
*/
}
//定义id排序比较器
public static class IdAscend implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.id - o2.id;
}
}
//定义按年龄和id排序,年龄相同时,按照id排序
public static class AgeIdAsecnd implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.age != o2.age ? (o1.age - o2.age) : o1.id - o2.id;
}
}
}
java比较器自定义排序
最新推荐文章于 2023-09-14 00:06:30 发布
这篇博客展示了如何使用Java的`Arrays.sort()`方法结合自定义比较器对学生对象进行排序。首先,根据ID升序排序,然后按照年龄和ID同时升序排序。代码中创建了两个比较器类`IdAscend`和`AgeIdAsecnd`,分别实现了排序逻辑。
摘要由CSDN通过智能技术生成