小明冒险记 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;
}
}
项目经理 : 终于搞定了
翌日,小明被开除了