CyberPlayerOne
CyberPlayerOne

Reputation: 3180

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

A pair consisting of two elements.

Can you please tell me how should I use Pair.class when calling the calculationSimilarity method? Because If I use String as K it worked but Pair here it doesn't work I got compling error.

Upvotes: 1

Views: 77

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213223

For HashMap<Pair<Long, Long>>, type parameter K is inferred as Pair<Long, Long>. So you need to pass Class<Pair<Long, Long>> but you're passing 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.

Upvotes: 3

Related Questions