Inheritance III: Subtype Polymorphism, Comparators, Comparable
11.1 A Review of Dynamic Method Selection
Static Type vs. Dynamic Type
static type: 变量声明时指定的类型。
dynamic type: 变量运行时的类型,根据 new 关键字。
11.2 ComparablesSubtype Polymorphism vs Explicit Higher Order Functions
Explicit Higher Order Functions:
def print_larger(x, y, compare, stringify):
if compare(x, y):
return stringify(x)
return stringify(y)
Subtype Polymorphism:
def print_larger(x, y):
if x.largerThan(y):
return x.str()
return y.str()
11.3 Comparables
java 有一个 comparable interface:
public interface Comparable<T> {
/*
Return negative number if o1 < o2.
Return 0 if o1 equals o2.
Return positive number if o1 > o2.
*/
public int compareTo(T obj);
}
Dog class implements the interface:
public class Dog implements Comparable<Dog> {
public int compareTo(Dog uddaDog) {
return this.size - uddaDog.size;
}
}
可以利用统一的 max() 函数来比较上面 Dog 类的大小了:
Dog[] dogs = new Dog[]{d1, d2, d3};
Dog largest = Collections.max(Arrays.asList(dogs));
11.4 Comparators
11.3 中的实现的问题是,只能比较 Dog 的 size 而没法比较 name 或者其他的属性。
这时候 java 还有一个 Comparator interface:
public interface Comparator<T> {
/*
Return negative number if o1 < o2.
Return 0 if o1 equals o2.
Return positive number if o1 > o2.
*/
int compare(T o1, T o2);
}
通过实现该 interface,可以比较任意属性:
import java.util.Comparator;
public class Dog {
private static class NameComparator implements Comparator<Dog> {
public int compare(Dog a, Dog b) {
return a.name.compareTo(b.name); // 这个 compareTo 是 java string 内置的比较函数
}
}
public static Comparator<Dog> getNameComparator() {
return new NameComparator();
}
}
Dog d1 = new Dog("dog1", 200);
Dog d2 = new Dog("dog2", 300);
Comparator<Dog> nc = Dog.getNameComparator();
int cmp = nc.compare(d1, d2);
Comparable 和 Comparator 的区别是 An object that implements Comparable can compare another object to itself, whereas a Comparator compares two objects other than itself.