`
snoopy7713
  • 浏览: 1129496 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

Comparator与Comparable的区别

    博客分类:
  • java
阅读更多

当需要排序的集合或数组不是单纯的数字类型的时候,通常可以使用Comparator或Comparable,以简单的方式实现对象排序或自定义排序。

Comparator和Comparable的区别如下:

Comparable用在对象本身,说明这个对象是可以被比较的,也就是说可以被排序的。(String和Integer之所以可以比较大小,是因为它们都实现了Comparable接口,并实现了compareTo()方法)。

Comparator用在对象外面,相当于定义了一套排序算法来排序。

下面通过具体的例子来理解Comparator和Comparable的区别:

 

Comparable

Java代码 
  1. package  com.tianjf;  
  2.   
  3. import  java.util.Arrays;  
  4.   
  5. public  class  User implements  Comparable<Object> {  
  6.   
  7.     private  String id;  
  8.     private  int  age;  
  9.   
  10.     public  User(String id, int  age) {  
  11.         this .id = id;  
  12.         this .age = age;  
  13.     }  
  14.   
  15.     public  int  getAge() {  
  16.         return  age;  
  17.     }  
  18.   
  19.     public  void  setAge(int  age) {  
  20.         this .age = age;  
  21.     }  
  22.   
  23.     public  String getId() {  
  24.         return  id;  
  25.     }  
  26.   
  27.     public  void  setId(String id) {  
  28.         this .id = id;  
  29.     }  
  30.   
  31.     @Override   
  32.     public  int  compareTo(Object o) {  
  33.         return  this .age - ((User) o).getAge();  
  34.     }  
  35.   
  36.     /**  
  37.      * 测试方法  
  38.      */   
  39.     public  static  void  main(String[] args) {  
  40.         User[] users = new  User[] { new  User("a"30 ), new  User("b"20 ) };  
  41.         Arrays.sort(users);  
  42.         for  (int  i = 0 ; i < users.length; i++) {  
  43.             User user = users[i];  
  44.             System.out.println(user.getId() + " "  + user.getAge());  
  45.         }  
  46.     }  
  47. }  


Comparator

Java代码 
  1. package  com.tianjf;  
  2.   
  3. import  java.util.Arrays;  
  4. import  java.util.Comparator;  
  5.   
  6. public  class  MyComparator implements  Comparator<Object> {  
  7.   
  8.     @Override   
  9.     public  int  compare(Object o1, Object o2) {  
  10.         return  toInt(o1) - toInt(o2);  
  11.     }  
  12.   
  13.     private  int  toInt(Object o) {  
  14.         String str = (String) o;  
  15.         str = str.replaceAll("一""1" );  
  16.         str = str.replaceAll("二""2" );  
  17.         str = str.replaceAll("三""3" );  
  18.         return  Integer.parseInt(str);  
  19.     }  
  20.   
  21.     /**  
  22.      * 测试方法  
  23.      */   
  24.     public  static  void  main(String[] args) {  
  25.         String[] array = new  String[] { "一""三""二"  };  
  26.         Arrays.sort(array, new  MyComparator());  
  27.         for  (int  i = 0 ; i < array.length; i++) {  
  28.             System.out.println(array[i]);  
  29.         }  
  30.     }  
  31. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics