Deriving a typical type from a generic type in Java (compile-time error)

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

 public static<T> List<T> sortMap(Map<T, Comparable> map) 

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

Now I want to pass a generic HashMap of type S

 Map<S,Double> map 

when calling a static function in a generic class that has a map as a member variable.

I gave an example of the minimum code below.

However, I get an error message ( S and T are both T, but in different areas 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 to solve this problem? I am surprised that Java does not allow deriving a generic type from a generic type. What structure in Java can be used to work with more abstract reasoning code?

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 } } 
+6
source share
1 answer

This is not a problem with T and S , but with Comparable and Double .

The cause of the error is that Map<T, Double> not Map<T, Comparable> .

You will have to slightly expand the scope of the second type parameter. Sort of:

 public static <T, S extends Comparable<S>> List<T> function(Map<T, S> map) { //implementation } 

Then you can call the method with:

 Map<S, Double> map = new HashMap<S, Double>(); function(map); 
+7
source

Source: https://habr.com/ru/post/989388/


All Articles