Comparable和Comparator接口

工作中偶然遇到了这个问题,需要根据某个类的某个成员变量来进行排序,然后就发现了Java中的这两个接口,Comparable和Comparator,本着求根问底的精神,今天把这里整理一下。

1、Comparable接口

  先看看Java中的源码(摘取一段注释)

 * This interface imposes a total ordering on the objects of each class that
 * implements it.  This ordering is referred to as the class's <i>natural
 * ordering</i>, and the class's <tt>compareTo</tt> method is referred to as
 * its <i>natural comparison method</i>.<p>
这个接口给每个实现它的类都“impose”了一个total ordering。这种ordering可以理解成这个类的“natural ordering”,这个natural ordering就是通过调用compareTo方法来实现的。

再接着看下面这一段

 * Lists (and arrays) of objects that implement this interface can be sorted
 * automatically by {@link Collections#sort(List) Collections.sort} (and
 * {@link Arrays#sort(Object[]) Arrays.sort}).  Objects that implement this
 * interface can be used as keys in a {@linkplain SortedMap sorted map} or as
 * elements in a {@linkplain SortedSet sorted set}, without the need to
 * specify a {@linkplain Comparator comparator}.<p>
所有实现了Comparable接口的这种类的对象的List可以直接使用Collections.sort(lis)来进行排序,而且实现了这个接口的对象可以作为SortedMap或者SortedSet的key而不需要再实现Comparator

举个例子

定义一个Student类:

class Student implements Comparable<Student>{
	public Student(String name, int age){
		this.name = name;
		this.age = age;
	}
	public String name;
	public int age;
	public int compareTo(Student o) {
		return name.compareTo(o.name);
	}	
}
Java中的String类实现了Comparable方法,“a”.compareTo("b")的值是-1;"b".compareTo("a")的值是1。

Student类实现了Comparable方法,就是按照name的顺序来进行排序。测试一下:

public class ComparableAndComparator {
	
	public static void main(String[] args){
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("abc", 10));
		list.add(new Student("Abd", 10));
		for(Student s : list)
			System.out.println(s.name);
		Collections.sort(list);
		for(Student s : list)
			System.out.println(s.name);
	}
	
}

输出结果是:

abc
Abd
Abd
abc

Collections.sort(list)是按照list中的object所实现的Comparable来进行升序排列的,而"abc">"Abd",因为a的ASCII码值是97,而A的ASCII码值是65,所以经过排序之后就是上述的结果了。

如果我现在在按照名字排序时忽略大小写应该怎么写呢?


2、Comparator接口

因为Student类已经实现了Comparable 接口按照name来进行排序,一种方法是修改Student中的compareTo方法实现这个需求。显然这种方式是不合理的呢,如果下次需要按照age来排序呢?所以正确的做法是实现Comparator接口

	public static void main(String[] args){
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("abc", 10));
		list.add(new Student("Abd", 10));
		for(Student s : list)
			System.out.println(s.name);
		Collections.sort(list, new Comparator<Student>() {

			public int compare(Student o1, Student o2) {
				// TODO Auto-generated method stub
				return o1.name.toLowerCase().compareTo(o2.name.toLowerCase());
			}
		});
		for(Student s : list)
			System.out.println(s.name);
	}
运行结果如下:

abc
Abd
abc
Abd


只需要在用Collections进行排序时实现Comparator这个接口,然后做你想做的事情就行了~

3、其实String类也有这样一个Comparator

    /**
     * A Comparator that orders <code>String</code> objects as by
     * <code>compareToIgnoreCase</code>. This comparator is serializable.
     * <p>
     * Note that this Comparator does <em>not</em> take locale into account,
     * and will result in an unsatisfactory ordering for certain locales.
     * The java.text package provides <em>Collators</em> to allow
     * locale-sensitive ordering.
     *
     * @see     java.text.Collator#compare(String, String)
     * @since   1.2
     */
    public static final Comparator<String> CASE_INSENSITIVE_ORDER
                                         = new CaseInsensitiveComparator();
    private static class CaseInsensitiveComparator
                         implements Comparator<String>, java.io.Serializable {
	// use serialVersionUID from JDK 1.2.2 for interoperability
	private static final long serialVersionUID = 8575799808933029326L;

        public int compare(String s1, String s2) {
            int n1=s1.length(), n2=s2.length();
            for (int i1=0, i2=0; i1<n1 && i2<n2; i1++, i2++) {
                char c1 = s1.charAt(i1);
                char c2 = s2.charAt(i2);
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }
    }
所以2中的程序可以改写为如下:

	public static void main(String[] args){
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("abc", 10));
		list.add(new Student("Abd", 10));
		for(Student s : list)
			System.out.println(s.name);
		Collections.sort(list, new Comparator<Student>() {

			public int compare(Student o1, Student o2) {
				// TODO Auto-generated method stub
				return String.CASE_INSENSITIVE_ORDER.compare(o1.name, o2.name);
			}
		});
		for(Student s : list)
			System.out.println(s.name);
	}
String类中的CASE_INSENSITIVE_ORDER比直接用toUpperCase再进行比较效率会高一些




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值