Comparator与Comparable的区别

http://zhanghu198901.iteye.com/blog/1575164

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

Comparator和Comparable的区别如下:

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

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

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

 

Comparable

  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

  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. }  


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值