从Java的泛型类型推导泛型(编译时错误) [英] Inferring a generic type from a generic type in Java (compile time error)
问题描述
我有一个具有以下签名的静态函数,用于泛型类型 T
public static< T>列表与LT; T> sortMap(Map< T,Comparable> map)
这应该返回带有某些属性的映射键列表。
现在我想传递一个类型为 S
$ b的泛型HashMap $ b
地图< S,Double>映射
在一个泛型类中调用静态函数,该泛型类将映射作为成员变量。 / b>
我在下面列出了一个最小代码示例。
但是,我收到一条错误消息( S
和 T
都是T,但在我的代码的不同范围内,即 T#1
= T
, T#2
= S
):
必需:Map< T#1,Comparable>找到
:Map< T#2,Double>
reason:无法推断类型变量T#1
(参数不匹配; Map< T#2,Double>不能转换为Map< T#1,Comparable>)
如何解决此问题?我很惊讶Java不允许从泛型类型推断泛型。在Java中可以使用什么结构来处理这种更抽象的代码推理?
代码:
public class ExampleClass< T> {
地图< T,Double>地图;
public ExampleClass(){
this.map = new HashMap();
}
//以下行会产生上述错误
List< T> sortedMapKeys = UtilityMethods.sortMap(map);
}
public class UtilityMethods {
public static< T>列表与LT; T> sortMap(Map< T,Comparable> map){
//以某种方式对地图进行排序并返回列表
}
}
这不是 T
和<$ c的问题$ c> S ,但是使用 Comparable
和 Double
。
导致错误的原因是 Map< T,Double>
不是 Map< T,Comparable>
。
您必须扩大第二个类型参数的范围。例如:
public static< T,S扩展了Comparable< S>>列表与LT; T>函数(Map< T,S> map){
//执行
}
<然后,您可以使用以下方法调用该方法:
Map< S,Double> map = new HashMap< S,Double>();
函数(地图);
I have a static function with the following signature for a generic type T
public static<T> List<T> sortMap(Map<T, Comparable> map)
which should return a list of map keys with some property.
Now I want to pass a generic HashMap of type S
Map<S,Double> map
in calling the static function within a generic class, which has the map as a member variable.
I have listed a minimal code example below.
However, I get an error message (S
and T
are both T's but in different scopes of my code, i.e. 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>)
How can resolve this issue? I am surprised that Java does not allow inferring a generic type from a generic type. What structure in Java can one use to work with that kind of more abstract code reasoning?
Code:
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
}
}
It's not the problem with the T
and S
, but with the Comparable
and Double
.
The reason for the error is that a Map<T, Double>
is not a Map<T, Comparable>
.
You'll have to widen a bit the scope of the second type-parameter. Something like:
public static <T, S extends Comparable<S>> List<T> function(Map<T, S> map) {
//implementation
}
Then, you'll be able to invoke the method with:
Map<S, Double> map = new HashMap<S, Double>();
function(map);
这篇关于从Java的泛型类型推导泛型(编译时错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!