Comparable接口实现集合的排序
Posted liuxuelin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Comparable接口实现集合的排序相关的知识,希望对你有一定的参考价值。
1.让需要排序的对象实现Comparable接口,并重写compareTo方法
public class Student implements Comparable<Student> { //泛型为需要排序的对象
private int age;
private String name; private int score; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Student(int age, String name, int score) { super(); this.age = age; this.name = name; this.score = score; }
@Override public int compareTo(Student other) { //参数为需要排序的对象 return score-other.getScore(); //表示通过分数score字段进行排序 } }
2.构造需要排序的对象的集合,并调用Collections.sort()方法对集合中元素进行排序:
public class CompareTest { public static void main(String[] args) { Student s1 = new Student(16, "aa", 44); Student s2 = new Student(18, "bb", 88); Student s3 = new Student(17, "cc", 99); Student s4 = new Student(19, "dd", 66); List<Student> students = Arrays.asList(s1, s2, s3, s4); Collections.sort(students); //对students按score字段进行排序 for (Student student : students) { System.out.println(student.getScore()); } } }
注意:使用 Collections.sort(students);方法对集合对象进行排序时,集合中的对象必须实现Comparable接口,否则报错
以上是关于Comparable接口实现集合的排序的主要内容,如果未能解决你的问题,请参考以下文章