【发布时间】:2015-06-19 08:43:46
【问题描述】:
我有一个带有以下泛型类型签名的静态函数T
public static<T> List<T> sortMap(Map<T, Comparable> map)
它应该返回具有某些属性的映射键列表。
现在我想传递一个 S 类型的通用 HashMap
Map<S,Double> map
在泛型类中调用静态函数,该类将映射作为成员变量。
我在下面列出了一个最小的代码示例。
但是,我收到一条错误消息(S 和 T 都是 T,但在我的代码的不同范围内,即 T#1 = T、T#2= S):
required: Map<T#1,Comparable>
found: Map<T#2,Double>
reason: cannot infer type-variable(s) T#1
(argument mismatch; Map<T#2,Double> cannot be converted to Map<T#1,Comparable>)
如何解决这个问题?我很惊讶 Java 不允许从泛型类型推断泛型类型。可以使用 Java 中的哪种结构来处理这种更抽象的代码推理?
代码:
public class ExampleClass<T> {
Map<T, Double> map;
public ExampleClass () {
this.map = new HashMap();
}
//the following line produces the mentioned error
List<T> sortedMapKeys = UtilityMethods.sortMap(map);
}
public class UtilityMethods {
public static<T> List<T> sortMap(Map<T, Comparable> map) {
// sort the map in some way and return the list
}
}
【问题讨论】:
-
请向观众展示课程代码。
-
static方法不能访问成员变量;你用的是什么版本的java? -
我认为您必须添加更多代码才能让我们理解问题。
-
顺便说一句,您不能使用
Map<S,Double>传递给需要Map<T, Comparable>的方法。Double和Comparable是具有不同继承层次结构的不同类型。