两个接口都是用来定义比较规则的
Comparable接口(用于在类内部定义比较规则,一个类只能定义一个)
public int compareTo(Dog o)
Comparator接口(在类外部定义比较规则,可以定义多个比较规则使用)
public int compare(Dog o1, Dog o2)
使用:
在一些排序的应用中将使用接口
比如:TreeSet和TreeMap
java.util.TreeSet.TreeSet<Dog>(Comparator<? super Dog> comparator)
TreeSet可以创建有序的集合,此时将使用到排序规则,上述使用的Dog对象要么实现comparable接口,
要么在创建TreeSet实例时传入Comparator作为比较规则使用
如果两者都没有,报错。
如果两者都有,将使用传入的Comparator对象作为比较规则
TreeMap的put方法:
public V put(K key, V value) {
....
....
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
//在这里开始判断,if 传入了Comparator对象,则使用这个对象的比较规则
//else 调用对象的Comparable.compareTo方法,
//如果对象没有实现Comparable接口,则不能强转成功,抛出异常
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
}