前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >比较器的使用

比较器的使用

原创
作者头像
大学里的混子
修改2019-02-18 11:24:46
6390
修改2019-02-18 11:24:46
举报
文章被收录于专栏:LeetCodeLeetCode

一.比较器的使用

代码语言:javascript
复制
private static class Student{
    int age;
    String name;
    int height;

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

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", height=" + height +
                '}';
    }
}

private static class isIncrease implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.height - o2.height;
    }
}

main函数里面:

代码语言:javascript
复制
Student[] students = new Student[]{
        new Student(12,"lvachao",23),
        new Student(14,"lvacha",678),
        new Student(34,"lvaco",87),
};

Arrays.sort(students,new isIncrease());
for (Student student : students){
    System.out.println(student);
}

定义一个student类,然后定义一个isIncrease类继承Comparator<Student>接口,注意这里的泛型的类型要添加上Student

  1. 如果返回的是负数,那么对象o1在前面;
  2. 如果返回的是正数,那么对象o2在前面;

代码语言:javascript
复制
上面程序输出:
Student{age=12, name='lvachao', height=23}
Student{age=34, name='lvaco', height=87}
Student{age=14, name='lvacha', height=678}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一.比较器的使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档