比较器比较类的属性之不修改实体类

来源:互联网 发布:打车软件有哪些 编辑:程序博客网 时间:2024/05/21 07:04

Comparator比较器

在集合当中,我们通常都会用到,或者说集合内部自己会调用。
比如:

  treeset使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。

但是如果我们在容器当中传入的是对象,这时候我们就无法更具具体的对象内部的属性进行比较了。
这时候需要我们自己来写一个比较器。


- 实体类

  • `public class Student {

    private int age;

    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 getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    private String name;
    private int id;

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

    @Override
    public String toString() {
    return “Student1 [age=” + age + “, name=” + name + “, id=” + id + “]”;
    }

}
`
这个类我们创建了实体类,Student里面有具体的属性,年龄,姓名,id

添加数据到 ArrayList容器中

public class Demo1 {    public static void main(String[] args) {        Student su1 = new Student(11, "a", 1);        Student su2 = new Student(12, "b", 2);        Student su3 = new Student(15, "c", 3);        Student su4 = new Student(13, "d",6);        Student su5 = new Student(13, "f", 4);        List list =new ArrayList<Student>();        list.add(su1);        list.add(su2);        list.add(su3);        list.add(su4);        list.add(su5);    }}

这里我们把学生对象的属性都添加进去了

输出

并没有按照年龄排序

自定义构造器

class Comparatora implements Comparator<Student> {    public int compare(Student arg0,Student arg1) {        if(arg0.getAge()>arg1.getAge()){            return -1;        }else if(arg0.getAge()==arg1.getAge()){            return arg0.getName().compareTo(arg1.getName());        }else{            return 1;        }    }

比较年龄,如果年龄相同就按照姓名来比较

Collections.sort方法进行排序

        Student su1 = new Student(11, "a", 1);        Student su2 = new Student(12, "b", 2);        Student su3 = new Student(15, "c", 3);        Student su4 = new Student(13, "d",6);        Student su5 = new Student(13, "f", 4);        List list =new ArrayList<Student>();        list.add(su1);        list.add(su2);        list.add(su3);        list.add(su4);        list.add(su5);        Collections.sort(list, new Comparatora());        System.out.println(list);

通过自定义方法,进行按照指定的要求进行排序,这样没有修改实体内,实现了Comparator接口的compare方法

1 0
原创粉丝点击