Double super wildcard

问题描述 投票:0回答:1

在这段代码中,第二行出现错误,而第一行成功编译:

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>

这是编译器缺陷还是在保护我免受某些侵害?

java generics lambda wildcard comparator
1个回答
1
投票

您将a定义为Comparator<? super Integer>,并且您的分配(x, y) -> Integer.compare(x, y)完成了它。

但是,编译器不知道确切的类型?是什么。它可能是ObjectNumberInteger本身,但是哪个未知。 thenComparing()依赖于a的类型参数,因为其签名为Comparator<T> thenComparing(Comparator<? super T>)。您正在传递Comparator<Integer>,但a的类型参数不匹配。

泛型是不变式Comparator<? super Integer>不是Comparator<Integer>。如果您不关心类型,请使用通配符。


a定义为Comparator<Integer>以进行修复。

© www.soinside.com 2019 - 2024. All rights reserved.