泛型在Eclipse中编译和运行,但不在javac中编译
2022-09-01 22:39:09
注意:这是可比和比较器合同的分拆,关于空
此代码在 Eclipse (20090920-1017
)
import java.util.*;
public class SortNull {
static <T extends Comparable<? super T>>
Comparator<T> nullComparableComparator() {
return new Comparator<T>() {
@Override public int compare(T el1, T el2) {
return
el1 == null ? -1 :
el2 == null ? +1 :
el1.compareTo(el2);
}
};
}
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(3, 2, 1, null, null, 0)
);
Comparator<Integer> numbersComp = nullComparableComparator();
Collections.sort(numbers, numbersComp);
System.out.println(numbers);
// "[null, null, 0, 1, 2, 3]"
List<String> names = new ArrayList<String>(
Arrays.asList("Bob", null, "Alice", "Carol")
);
Comparator<String> namesComp = nullComparableComparator();
Collections.sort(names, namesComp);
System.out.println(names);
// "[null, Alice, Bob, Carol]"
}
}
然而,它没有编译在.这是错误消息:javac 1.6.0_17
SortNull.java:17: incompatible types; no instance(s) of type variable(s) T exist
so that java.util.Comparator<T> conforms
to java.util.Comparator<java.lang.Integer>
found : <T>java.util.Comparator<T>
required: java.util.Comparator<java.lang.Integer>
Comparator<Integer> numbersComp = nullComparableComparator();
SortNull.java:25: incompatible types; no instance(s) of type variable(s) T exist
so that java.util.Comparator<T> conforms
to java.util.Comparator<java.lang.String>
found : <T>java.util.Comparator<T>
required: java.util.Comparator<java.lang.String>
Comparator<String> namesComp = nullComparableComparator();
2 errors
有人可以解释为什么会出现这种差异吗?这是一个错误吗?如果是这样,谁有这个错误?