Mar*_*nik 6 java type-inference java-8
在回答问题时,我遇到了Java类型推断的这种奇怪行为.以下工作没有问题:
new HashMap<String,Integer>().entrySet().stream()
.sorted(Map.Entry.comparingByValue());
Run Code Online (Sandbox Code Playgroud)
但如果我们.reversed()最后添加,它会突然失败:
new HashMap<String,Integer>().entrySet().stream()
.sorted(Map.Entry.comparingByValue().reversed());
Run Code Online (Sandbox Code Playgroud)
细节:在第一种情况下,comparingByValue()推断类型为Comparator<Map.Entry<String, Integer>>,但在第二种情况下,它更改为Comparator<Map.Entry<Object, V>>.
类型reversed()只是Comparator<T>对其目标类型的身份转换.为什么类型推断会在这样一个看似微不足道的步骤中失去它?我无法摆脱预感,这必定是由于推断机制中的一个错误.
作为进一步的难题,如果我们只是内联实现reversed(),那就是return Collections.reverseOrder(this);:
new HashMap<String,Integer>().entrySet().stream()
.sorted(reverseOrder(Map.Entry.comparingByValue());
Run Code Online (Sandbox Code Playgroud)
它又有效了.