Map.Entry.comparingByValue().reversed()的类型是什么? [英] What is the type of Map.Entry.comparingByValue().reversed()?

查看:309
本文介绍了Map.Entry.comparingByValue().reversed()的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图条目列表

Map<String, Integer> map = new HashMap<>();
...(fill the map)...
List<Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());

,我想根据此答案按值对它进行排序,但顺序相反.当我这样做

and I want to sort it by values according to this answer, but in reverse order. When I do

Comparator<Entry<String, Integer>> cmp = Entry.comparingByValue();
entries.sort(cmp.reversed());

一切正常.但是当我尝试将以上两行缩短为

everything works fine. But when I try to shorten the above two lines to

entries.sort(Entry.comparingByValue().reversed());

编译器返回

error: incompatible types: Comparator<Entry<Object,V>> cannot be converted to Comparator<? super Entry<String,Integer>>
        entries.sort(Entry.comparingByValue().reversed());
  where V is a type-variable:
    V extends Comparable<? super V>

这似乎很奇怪,因为比较器的reversed()默认方法的实现只是将其转移到Collections.reverseOrder(),我可以将上面的行更改为

This seems strange because the implementation of Comparator's reversed() default method simply transfers it to Collections.reverseOrder() and I can change the above line to

entries.sort(Collections.reverseOrder(Entry.comparingByValue()));

上班.但是Entry.comparingByValue().reversed()的正确类型是什么?

to work. But what is the correct type of Entry.comparingByValue().reversed()?

Comparator<Entry<String, Integer>> cmp = Entry.comparingByValue().reversed();

似乎不起作用.省略类型参数Entry<String, Integer>是可行的,但这会在以后导致编译器发出未经检查的方法调用"警告.

doesn't seem to work. Omitting the type parameter Entry<String, Integer> works, but this results in "unchecked method invocation" warning from the compiler later.

推荐答案

在这种情况下,编译器不够聪明,无法推断泛型类型参数.您可以明确指定它们:

The compiler is not clever enough to infer the generic type parameters in this case. You can specify them explicitly:

entries.sort(Entry.<String, Integer>comparingByValue().reversed());

问题是您首先需要comparingByValue返回的比较器的类型,才能知道reversed返回的比较器的类型.

The issue is that you first need the type of the comparator returned by comparingByValue to know the type of the one returned by reversed.

我看不出任何聪明的编译器无法向后工作的原因,并且知道sort需要特定类型,因此reversed必须为特定类型,因此comparingByValue必须为特定类型.但这不是事实.

I don't see any good reason why a clever compiler couldn't work backwards and know that sort requires a particular type, so reversed must be a particular type, so comparingByValue must be a particular type. But that's not how things are.

类型推断仍在研究中(最近出现在Java 10中),所以也许在未来,谁知道.

Type inference is still being worked on (as recently as Java 10), so maybe in the future, who knows.

这篇关于Map.Entry.comparingByValue().reversed()的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆