在这段代码中,第二行出现错误,而第一行成功编译:
Comparator<? super Integer> a = (x, y) -> Integer.compare(x, y);
Comparator<? super Integer> b = a.thenComparing((x, y) -> Integer.compare(x, y));
错误是“不兼容的类型:无法将对象转换为int”
thenComparing
具有以下签名:thenComparing(Comparator<? super T> other)
,因此据我所知other
在这种情况下将变成Comparator<? super super T>
或Comparator<? super super Integer>
。
为什么在我的示例中它变成Comparator<Object>
?
这是编译器缺陷还是在保护我免受某些侵害?
您将a
定义为Comparator<? super Integer>
,并且您的分配(x, y) -> Integer.compare(x, y)
完成了它。
但是,编译器不知道确切的类型?
是什么。它可能是Object
,Number
或Integer
本身,但是哪个未知。 thenComparing()
依赖于a
的类型参数,因为其签名为Comparator<T> thenComparing(Comparator<? super T>)
。您正在传递Comparator<Integer>
,但a
的类型参数不匹配。
泛型是不变式。 Comparator<? super Integer>
不是Comparator<Integer>
。如果您不关心类型,请使用通配符。
将a
定义为Comparator<Integer>
以进行修复。