我有一个静态函数,其泛型类型T具有以下签名
public static List sortMap(Map map)
应返回带有某些属性的地图键列表.
现在我想传递S类型的通用HashMap
Map map
调用泛型类中的静态函数,该类将映射作为成员变量.
我在下面列出了一个最小的代码示例.
但是,我收到一条错误消息(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不允许从泛型类型推断泛型类型. 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
}
}