www.zhblog.net

Java Comparable 接口

Comparable 接口 compareTo 方法应该兼容 equals 方法:当 x.equals(y) 时,x.compareTo(y) 应该等于 0。

大多数类都是遵循这一原则。但典型的 BigDecimal 没有遵循

假设 x = new BigDecimal("1.0") ,y = new BigDecimal("1.00")

此时,x.equals(y) 等于 false,x.compareTo(y) 等于 0。


带有继承关系的接口方法实现

class Employee implements Comparable<Employee>{





   String name;

   int age;





   public String getName() {

      return name;

   }





   public void setName(String name) {

      this.name = name;

   }





   public int getAge() {

      return age;

   }





   public void setAge(int age) {

      this.age = age;

   }





   public Employee() {};





   public Employee(String name, int age) {

      super();

      this.name = name;

      this.age = age;

   }





   public static String staticString() {

      return "static method.";

   }





   @Override

   public String toString() {

      return String.format("%s[name=%s, age=%d]", getClass().getName(), this.name, this.age);

   }





   @Override

   public int compareTo(Employee o) {

      return Integer.compare(this.age, o.age);

   }

}


Manager 继承 Employee,并且重写 compareTo 方法。

public class Manager extends Employee {





    public int order;





    public Manager(String name, int age, int order) {

        super(name, age);

        this.order = order;

    }





    public int getOrder() {

        return order;

    }





    public void setOrder(int order) {

        this.order = order;

    }





    @Override

    public String toString() {

        return String.format("%s[name=%s, age=%d, order=%d]", getClass().getName(), this.name, this.age, this.order);

    }





    @Override

    public int compareTo(Employee o) {

        Manager other = (Manager) o;

        return Integer.compare(this.order, other.order);

    }

}


测试

Employee[] employees = {new Manager("a", 2, 1), new Manager("b", 1, 2), new Manager("c", 3, 3)};

Arrays.sort(employees);

System.out.println(Arrays.toString(employees));


Employee[] employees = {new Employee("a", 2), new Employee("b", 1), new Employee("c", 3)};

Arrays.sort(employees);

System.out.println(Arrays.toString(employees));


  

  

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情