java对象排序
一、前言
有时我们需要对类按照类中的某一个属性(或者多个属性)来对类的对象进行排序,有两种方法可以实现,
一种方法是类实现Comparable<T>接口,然后调用Collections.sort(List)方法进行排序,
另一种方法是类不实现Comparable<T>接口,而在排序时使用Collections.sort(List, Comparator<T>)方法,并实现其中的Comparator<T>接口。
二、排序实现
假设有一个学生类Student,包含两个属性:姓名name,年龄age,如下:
public class Student { private String name; private int age; ....get.set }
1、通过类实现Comparable<T>接口进行排序
public class Student implements Comparable<Student>{ private String name; private int age; ...get.set /** * 将对象按姓名字典序升序排序 * @param o * @return */ @Override public int compareTo(Student o) { return this.name.compareTo(o.getName()); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
测试
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Client { public static void main(String[] args){ List<Student> students = new ArrayList<>(); students.add(new Student("a", 18)); students.add(new Student("c", 19)); students.add(new Student("b", 20)); Collections.sort(students); for(Student student:students){ System.out.println(student.toString()); } } }
输出
Student{name='a', age=18} Student{name='b', age=20} Student{name='c', age=19}
2、通过在Collections.sort()方法中实现Comparable<T>接口来实现排序
实体类不实现Comparable接口
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Client { public static void main(String[] args){ List<Student> students = new ArrayList<>(); students.add(new Student("a", 18)); students.add(new Student("c", 19)); students.add(new Student("b", 20)); Collections.sort(students, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1); } }); for(Student student:students){ System.out.println(student.toString()); } } }
结果:
Student{name='b', age=20} Student{name='c', age=19} Student{name='a', age=18}
可以看到学生按年龄从大到小排序输出。使用这种方法时要注意在比较函数compare的返回值中要包含0(年龄相等),不然可能会出现Comparison method violates its general contract!异常。
三、总结
无论使用上面的哪一种方法,对对象排序的核心是实现比较函数,其中第二种方法比第一种方法更加灵活。
摘自:https://www.cnblogs.com/sench/p/8889435.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律