[英]generic as a generic type in Java?
I have this method 我有这个方法
static public <K> float calculateSimilarity(HashMap<K, Float> hashMap1, Class<K> clazz)
In the part I call this method it is like this: 在我称之为方法的部分中,它是这样的:
HashMap<Pair<Long,Long>,Float> newValues1=....; //A.K.A. K is Pair<Long,Long> type.
calculateSimilarity(newValue1, Pair.class); // Doesn't work here!
where Pair is 哪对是
org.apache.commons.lang3.tuple.Pair
org.apache.commons.lang3.tuple.Pair
A pair consisting of two elements.
一对由两个元素组成。
Can you please tell me how should I use Pair.class when calling the calculationSimilarity method? 你能告诉我在调用calculateSimilarity方法时应该如何使用Pair.class? Because If I use String as K it worked but Pair here it doesn't work I got compling error.
因为如果我使用String作为K它工作但是在这里它不起作用我得到了编译错误。
For HashMap<Pair<Long, Long>>
, type parameter K
is inferred as Pair<Long, Long>
. 对于
HashMap<Pair<Long, Long>>
,类型参数K
被推断为Pair<Long, Long>
。 So you need to pass Class<Pair<Long, Long>>
but you're passing Class<Pair>
. 所以你需要传递
Class<Pair<Long, Long>>
但你传递的是Class<Pair>
。 You need to use appropriate cast: 你需要使用适当的演员:
calculateSimilarity(newValue1, (Class<Pair<Long, Long>>)(Class<?>)Pair.class);
The cast is required because you can't directly get the required Class
type using .class
literal. 强制转换是必需的,因为您无法使用
.class
文字直接获取所需的Class
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.