从Java中的generics类型推断generics类型(编译时错误)
我有一个静态函数,带有以下签名的generics类型T
public static List sortMap(Map map)
应返回带有某些属性的地图键列表。
现在我想传递S
类型的通用HashMap
Map map
在generics类中调用静态函数,该类具有映射作为成员变量。
我在下面列出了一个最小的代码示例。
但是,我收到一条错误消息( S
和T
都是T,但在我的代码的不同范围内,即T#1
= T
, T#2
= S
):
required: Map found: Map reason: cannot infer type-variable(s) T#1 (argument mismatch; Map cannot be converted to Map)
怎么解决这个问题? 我很惊讶Java不允许从generics类型推断generics类型。 Java中的哪种结构可以用来处理那种更抽象的代码推理?
代码 :
public class ExampleClass { Map map; public ExampleClass () { this.map = new HashMap(); } //the following line produces the mentioned error List sortedMapKeys = UtilityMethods.sortMap(map); } public class UtilityMethods { public static List sortMap(Map map) { // sort the map in some way and return the list } }
这不是T
和S
的问题,而是Comparable
和Double
。
出错的原因是Map
不是Map
。
你将不得不扩大第二个类型参数的范围。 就像是:
public static > List function(Map map) { //implementation }
然后,您将能够使用以下方法调用该方法:
Map map = new HashMap(); function(map);