zoukankan      html  css  js  c++  java
  • Java对象排序两种方法

    转载:https://blog.csdn.net/wangtaocsdn/article/details/71500500

    有时候需要对对象列表或数组进行排序,下面提供两种简单方式:

    方法一:将要排序的对象类实现Comparable<>接口。

    首先,创建学生类,我们将根据学生成绩对学生进行排序:

    /**
    * 学生类
    */
    class Student implements Comparable<Student>{

    String name;
    int age;
    int score;

    public Student(String name, int age,int score) {
    this.name = name;
    this.age = age;
    this.score = score;
    }

    @Override
    public int compareTo(Studento) {
    // TODO Auto-generated method stub
    return this.age - o.age;
    }
    }

    public class Test {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    ArrayList<Student> students = new ArrayList<>();
    students.add(new Student("大铭", 19, 89));
    students.add(new Student("来福", 26, 90));
    students.add(new Student("仓颉", 23, 70));
    students.add(new Student("王磊", 18, 80));

    System.out.println("排序前:");
    for (Student student : students) {
    System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
    }

    // 排序
    Collections.sort(students);

    System.out.println("排序后:");
    for (Student student : students) {
    System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
    }
    }
    }

    同理,也可以根据对象的其他属性进行排序。

    方法二:使用Comparator匿名内部类实现。

    还是使用同一个例子,按成绩将学生排序:

    /**
    * 学生类
    */
    class Student {

    String name;
    int age;
    int score;

    public Student(String name, int age,int score) {
    this.name = name;
    this.age = age;
    this.score = score;
    }
    }

    public class Test {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    ArrayList<Student> students = new ArrayList<>();
    students.add(new Student("大铭", 19, 89));
    students.add(new Student("来福", 26, 90));
    students.add(new Student("仓颉", 23, 70));
    students.add(new Student("王磊", 18, 80));

    System.out.println("排序前:");
    for (Student student : students) {
    System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
    }

    Collections.sort(students,new Comparator<Student>() {

    @Override
    public int compare(Student o1, Student o2) {
    // TODO Auto-generated method stub
    return o1.age-o2.age;
    }
    });

    System.out.println("排序后:");
    for (Student student : students) {
    System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
    }
    }
    }

    也可以实现按对象属性将对象列表排序。

  • 相关阅读:
    2020-01月-02月
    Work needing Technologies
    gcc和 gdb工具(转)
    pyenv and grunt-contrib-testem
    Statistics Books
    HTML5学习--SVG全攻略(基础篇)
    一个完整的学院网站实现过程
    JavaScript 常用单词整理
    一张图教会CSS3倒影
    Python大数据处理案例
  • 原文地址:https://www.cnblogs.com/ConfidentLiu/p/10410080.html
Copyright © 2011-2022 走看看