`

Comparater与Comparable的区别

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

Comparator和Comparable的区别如下:
引用
Comparable用在对象本身,说明这个对象是可以被比较的,也就是说可以被排序的。(String和Integer之所以可以比较大小,是因为它们都实现了Comparable接口,并实现了compareTo()方法)。
引用
Comparator用在对象外面,相当于定义了一套排序算法来排序。

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

Comparable

import java.util.Arrays;  
  
public class User implements Comparable<Object> {  
  
    private String id;  
    private int age;  
  
    public User(String id, int age) {  
        this.id = id;  
        this.age = age;  
    }  
  
    public int getAge() {  
        return age;  
    }  
  
    public void setAge(int age) {  
        this.age = age;  
    }  
  
    public String getId() {  
        return id;  
    }  
  
    public void setId(String id) {  
        this.id = id;  
    }  
  
    @Override  
    public int compareTo(Object o) {  
        return this.age - ((User) o).getAge();  
    }  
  
    /** 
     * 测试方法 
     */  
    public static void main(String[] args) {  
        User[] users = new User[] { new User("a", 30), new User("b", 20) };  
        Arrays.sort(users);  
        for (int i = 0; i < users.length; i++) {  
            User user = users[i];  
            System.out.println(user.getId() + " " + user.getAge());  
        }  
    }  
}  

Comparator

import java.util.Arrays;  
import java.util.Comparator;  
  
public class MyComparator implements Comparator<Object> {  
  
    @Override  
    public int compare(Object o1, Object o2) {  
        return toInt(o1) - toInt(o2);  
    }  
  
    private int toInt(Object o) {  
        String str = (String) o;  
        str = str.replaceAll("一", "1");  
        str = str.replaceAll("二", "2");  
        str = str.replaceAll("三", "3");  
        return Integer.parseInt(str);  
    }  
  
    /** 
     * 测试方法 
     */  
    public static void main(String[] args) {  
        String[] array = new String[] { "一", "三", "二" };  
        Arrays.sort(array, new MyComparator());  
        for (int i = 0; i < array.length; i++) {  
            System.out.println(array[i]);  
        }  
    }  
}  


转自:http://zhanghu198901.iteye.com/blog/1575164
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics