首页 > 编程语言 > 详细

Comparable接口实现集合的排序

时间:2018-12-16 15:45:09      阅读:153      评论:0      收藏:0      [点我收藏+]

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接口实现集合的排序

原文:https://www.cnblogs.com/liuxuelin/p/10126743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!