- 介绍
Comparable<T>接口和Comparator<T>接口都是JDK中提供的和比较相关的接口。使用它们可以对对象进行比较大小,排序等操作。这算是之后排序的先导知识吧。
Comparable, 字面意思是“可以比较的”,所以实现它的类的多个实例应该可以相互比较“大小”或者“高低”等等。
Comparator, 字面意思是“比较仪,比较器”, 它应该是专门用来比较用的“工具”。 -
Comparable
Comparable<T>接口public interface Comparable<T> { public int compareTo(T o); }
首先看看JDK中怎么说的:
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>
大意是: 任何实现这个接口的类,其多个实例能以固定的次序进行排列。次序具体由接口中的方法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}).
如果某个类实现了这个接口,则它的List或数组都能使用Collections.sort()或Arrays.sort()进行排序。
常见的类如Integer, Double, String都实现了此类。一会儿会结合源码进行分析。
我们先来看Integer中的实现:
public final class Integer extends Number implements Comparable<Integer> {
private final int value;
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
我们只贴出了和比较相关的方法。
可以看到,compareTo方法其中调用了compare方法,这是JDK1.7增加的方法。在Integer中新增这个方法是为了减少不必要的自动装箱拆箱。传入compare方法的是两个Integer的值x和y。
如果x < y, 返回-1;如果x = y, 返回0;如果x > y, 返回1。
顺便一说,JDK中的实现非常简洁,只有一行代码, 当判断情况有三种时,使用这种嵌套的判断 x ? a : b 可以简洁不少,这是该学习的。
后面的compareUnsigned是JDK1.8新加入的方法, 用来比较无符号数。这里的无符号数意思是默认二进制最高位不再作为符号位,而是计入数的大小。
其实现是
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}