Student外部比较器比较年龄,身高,名字

实体类和外部比较器类代码如下所示:

package com.test.Test09;


import java.util.Comparator;

public class Student{
    private int age;
    private double height;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

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


}

class BiJiao01 implements Comparator<Student> {


    @Override
    public int compare(Student o1, Student o2) {
        //return 0;
        //比较年龄
        return o1.getAge()-o2.getAge();
    }
}

class BiJiao02 implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        //比较姓名
        return o1.getName().compareTo(o2.getName());
    }
}

class BiJiao03 implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        //在年龄相同的情况下比较身高,年龄不同比较年龄
        if(o1.getAge()-o2.getAge() == 0) {
            return ((Double)(o1.getHeight())).compareTo((Double)(o2.getHeight()));
        }else{ //年龄不一样
            return o1.getAge()-o2.getAge();
        }
    }
}

测试类如下所示:
package com.test.Test09;

import com.test.Test09.Student;

public class Test02 {
    public static void main(String[] args) {
        //比较两个学生
        Student s1 = new Student(9, 160.2, "alili");
        Student s2 = new Student(14, 170.5, "bnana");
        /*//获取外部比较器
        BiJiao01 bj1 = new BiJiao01();
        //1.比较年龄
        System.out.println(bj1.compare(s1,s2)); //0 -5*/

        /*//获取外部比较器
        BiJiao02 bj2 = new BiJiao02();
        //2.比较姓名
        System.out.println(bj2.compare(s1,s2)); // 2 -1*/

        //3.在年龄相同的情况下比较身高,年龄不同比较年龄
        BiJiao03 bj3 = new BiJiao03();
        System.out.println(bj3.compare(s1,s2));//-5
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值