TreeSet(Comparator<? super E> comparator) ,根据<? super E>传入比较器的类应该是E或者是E的父类,但是实际用的时候却不一样。比如Student是Person的子类。
public class Text implements Comparator<Person>{
public int compare(Person p1, Person p2) {
int num = new Integer(p1.age).compareTo(new Integer(p2.age));
return num==0?p1.name.compareTo(p2.name):num;
}
}
这样写下面代码可以正常运行
TreeMap<Student,Integer> treeMap = new TreeMap<Student,Integer>(new Text());
treeMap.put(new Student("LiLi",23), 016);
treeMap.put(new Student("ZhouLi",25), 036);
treeMap.put(new Student("LuRong",21), 066);
treeMap.put(new Student("XiLi",29), 046);
treeMap.put(new Student("JiangDi",24), 026);
System.out.println(treeMap);
但是奇怪的是我比较器里比的是Person对象,根据<? super E>,E就应该代表的是Person,这样比较器里就只能比较Person类对象或者它的父类对象,为什么Student能比较呢?如果从多态中子类当父类来回答是解释的通的,但是从<? super E>的角度你怎么解释呢?
如果把代码换成下面的:
public class Text implements Comparator<Student>{
public int compare(Student p1, Student p2) {
int num = new Integer(p1.age).compareTo(new Integer(p2.age));
return num==0?p1.name.compareTo(p2.name):num;
}
}
TreeMap<Person,Integer> treeMap2 = new TreeMap<Person,Integer>(new Text());
treeMap2.put(new Person("ZhangLi",35), 1057);
treeMap2.put(new Person("Lisi",36), 1077);
treeMap2.put(new Person("Weihua",35), 1057);
treeMap2.put(new Person("LuRong",40), 1457);
treeMap2.put(new Person("XiaoWei",39), 1457);
treeMap2.put(new Person("ZhongJing",38), 157);
System.out.println(treeMap2);
编译时这new TreeMap<Person,Integer>(new Text());一句会报错,提示是The constructor TreeMap<Person,Integer>(Text) is undefined。从这代码可以看出TreeSet(Comparator<? super E> comparator)中的E代表的就是Student,那么按<? super E>,比较器也应该可以比较Person,因为Person是Student的父类呀。我觉得把TreeSet(Comparator<? super E> comparator)改成TreeSet(Comparator<? extends E> comparator)就能理解。
还有一个问题:
public class Text implements Comparator<? super Student>{
public int compare(Student p1, Student p2) {
int num = new Integer(p1.age).compareTo(new Integer(p2.age));
return num==0?p1.name.compareTo(p2.name):num;
}
}
public class Text implements Comparator<? extends Person>{
public int compare(Student p1, Student p2) {
int num = new Integer(p1.age).compareTo(new Integer(p2.age));
return num==0?p1.name.compareTo(p2.name):num;
}
}
“public class Text implements Comparator<? super Student>{”和“public class Text implements Comparator<? extends Person>{”都会报“The type Text cannot extend or implement Comparator<? extends Person>. A supertype may not specify any wildcard”。是什么原因? |