小明冒险记 01

小明冒险记 01

这一天,小明来到鹅厂

项目经理 : 小明,来需求了,对Employee类进行排序,不能使用继承

小明 : 好的,那我使用Comparable接口好了

public class Employee implements Comparable{
    public String name;
    public double salary;


    @Override
    public int compareTo(Object o) {
        Employee other = (Employee) o;
        return (int) (salary - other.salary);
    }
}

小明 : 这样可以吗?

项目经理 : 你傻呀,Comparable不是支持泛型吗?

小明 : 哦,对哦

public class Employee implements Comparable<Employee>{
    public String name;
    public double salary;


    @Override
    public int compareTo(Employee other) {
        return (int) (salary - other.salary);
    }
}

项目经理 : 终于可以交货了,这彩笔

项目经理气冲冲的回来

项目经理 : 你不知道将double类型转换为int类型会损失精度吗?可以用Double类的静态方法来进行比较呀

小明 : 哦,知道了

public class Employee implements Comparable<Employee>{
    public String name;
    public double salary;


    @Override
    public int compareTo(Employee other) {
        return Double.compare(salary,other.salary);
    }
}

项目经理 : 小明,小明. 新加一个经理类,

小明 : 哦,知道了

public class Manager extends Employee {
    @Override
    public int compareTo(Employee o) {
        Manager other = (Manager) o;
        return Double.compare(salary,other.salary);
    }
}

项目经理 (幽幽的望过来) : 这样的话,Manager 和Employee比较是没有问题的,但是Employee这么和Manager比较呢?

小明 : 对哦,那Manager和Emaployee就不要比较了

public class Employee implements Comparable<Employee>{
    public String name;
    public double salary;

    @Override
    public int compareTo(Employee other) {
        if (getClass() != other.getClass()) {
            throw new ClassCastException();
        }
        return Double.compare(salary,other.salary);
    }
}
public class Manager extends Employee {
    @Override
    public int compareTo(Employee o) {
        if (getClass() != o.getClass()) {
            throw new ClassCastException();
        }
        Manager other = (Manager) o;
        return Double.compare(salary,other.salary);
    }
}

项目经理 : 小明,需求改动了,在加一个排序条件,经理无论工资多少都要排在员工前面

小明 : 哦,那我使用rank来进行比较吧

public class Employee implements Comparable<Employee>{
    public String name;
    public double salary;


    @Override
    final public int compareTo(Employee other) {
        if (Integer.compare(rank(),other.rank()) == 0){
            return Double.compare(salary,other.salary);
        }
        return Integer.compare(rank(),other.rank());
    }

    public int rank(){
        return 10;
    }
}
public class Manager extends Employee {
    @Override
    public int rank() {
        return 100;
    }
}

项目经理 : 终于搞定了

翌日,小明被开除了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值