java泛型推导,从Java的泛型类型推导泛型(编译时错误)

I have a static function with the following signature for a generic type T

public static List sortMap(Map map)

which should return a list of map keys with some property.

Now I want to pass a generic HashMap of type S

Map 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

found: Map

reason: cannot infer type-variable(s) T#1

(argument mismatch; Map cannot be converted to Map)

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 {

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

}

}

解决方案

It's not the problem with the T and S, but with the Comparable and Double.

You'll have to widen a bit the scope of the second type-parameter. Something like:

public static > List function(Map map) {

//implementation

}

Then, you'll be able to invoke the method with:

Map map = new HashMap();

function(map);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值