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值?内存地址?

你可能感兴趣的:(thread,算法)