首页  >  文章  >  Java  >  java中实现对类的对象进行排序

java中实现对类的对象进行排序

王林
王林转载
2019-12-11 17:51:453170浏览

java中实现对类的对象进行排序

我们需要对类按照类中的某一个属性(或者多个属性)来对类的对象进行排序,有两种方法可以实现,一种方法是类实现Comparable8742468051c85b06f0a0af9e3e506b5c接口,然后调用Collections.sort(List)方法进行排序,另一种方法是类不实现Comparable8742468051c85b06f0a0af9e3e506b5c接口,而在排序时使用Collections.sort(List, Comparator8742468051c85b06f0a0af9e3e506b5c)方法,并实现其中的Comparator8742468051c85b06f0a0af9e3e506b5c接口。

免费学习视频教程推荐:java视频教程

先创建一个简单的学生类:

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、通过类实现Comparable8742468051c85b06f0a0af9e3e506b5c接口进行排序

public class Student implements Comparable<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;
    }
 
    /**
     * 将对象按姓名字典序升序排序
     * @param o
     * @return
     */
    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.getName());
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "name=&#39;" + name + &#39;\&#39;&#39; +
                ", age=" + age +
                &#39;}&#39;;
    }
}

2、通过在Collections.sort()方法中实现Comparable8742468051c85b06f0a0af9e3e506b5c接口来实现排序

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());
        }
    }
 
}

相关文章教程推荐:java编程入门

以上是java中实现对类的对象进行排序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:csdn.net。如有侵权,请联系admin@php.cn删除