Comparator和Comparable的区别如下:
Comparable用在对象本身,说明这个对象是可以被比较的,也就是说可以被排序的。(String和Integer之所以可以比较大小,是因为它们都实现了Comparable接口,并实现了compareTo()方法)。
Comparator用在对象外面,相当于定义了一套排序算法来排序。
下面通过具体的例子来理解Comparator和Comparable的区别:
Comparable
package com.tianjf; 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
package com.tianjf; 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]); } } }