Java6.0中Comparable接口与Comparator接口详解 上

Part I

Comparable与Comparator接口不仅在串法上相似,而且他们的作用都十分的相似,他们可以让对象实现可排序。

首先让我们看看官方文档(JDK6.0 API)中对他们的描述:

public interface Comparable<T>

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

public interface Comparator<T>

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such asCollections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

从上描述可以知道,Comparable是让实体类去实现的,而实现了这个接口的实体类的本身就具备了对象间的可比较性。

而实现Comparator接口的类则是一个单纯可比较算法的实现。

 

Part II

下面是一个Person的实体类定义:

   1: public class Person {
   2:     
   3:     private String name;
   4:     private int age;
   5:     
   6:     public String getName() {
   7:         return name;
   8:     }
   9:     
  10:     public void setName(String name) {
  11:         this.name = name;
  12:     }
  13:     
  14:     public int getAge() {
  15:         return age;
  16:     }
  17:     
  18:     public void setAge(int age) {
  19:         this.age = age;
  20:     }
  21:     
  22: }

那如何让Person的对象根据name来实现对比呢?首先我们尝试一下在对象间直接使用逻辑运算符进行操作:

   1: public class CompareTest {
   2:     
   3:     public static void main(String[] args) {
   4:         Person p1 = new Person();
   5:         p1.setName("P1");
   6:         p1.setAge(20);
   7:         
   8:         Person p2 = new Person();
   9:         p2.setName("P2");
  10:         p2.setAge(30);
  11:         
  12:         System.out.println(p1 > p2);
  13:     }
  14:     
  15: }

结果如下:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The operator > is undefined for the argument type(s) Person, Person

    at CompareTest.main(CompareTest.java:12)

 

看来直接用逻辑运算符是没办法判断两个对象大小,其实自己想想也知道,如果用逻辑运算符来判断两个对象的大小,那应该用对象的什么来作为判断条件呢?名字?年龄?hashCode值?内存地址?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值