java中如何实现对类的对象进行排序
我们需要对类按照类中的某一个属性(或者多个属性)来对类的对象进行排序,有两种方法可以实现,一种方法是类实现Comparable
保定ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!
先创建一个简单的学生类:
public class Student { private String name; private int age; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
1、通过类实现Comparable
public class Student implements Comparable{ private String name; private int age; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } /** * 将对象按姓名字典序升序排序 * @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 + '}'; } }
2、通过在Collections.sort()方法中实现Comparable
public class Client { public static void main(String[] args){ Liststudents = 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 () { @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()); } } }
以上就是java中实现对类的对象进行排序的详细内容,感谢大家对创新互联的支持。
网站栏目:java中如何实现对类的对象进行排序
链接分享:http://scjbc.cn/article/jgcgpi.html