Inferring a generic type from a generic type in Java (compile time error) -
i have static function following signature generic type t
public static<t> list<t> sortmap(map<t, comparable> map) which should return list of map keys property.
now want pass generic hashmap of type s
map<s,double> map in calling static function within generic class, has map member variable.
i have listed minimal code example below.
however, error message (s , t both t's in different scopes of 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 converted map<t#1,comparable>) how can resolve issue? surprised java not allow inferring generic type generic type. structure in java can 1 use work 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 mentioned error list<t> sortedmapkeys = utilitymethods.sortmap(map); } public class utilitymethods { public static<t> list<t> sortmap(map<t, comparable> map) { // sort map in way , return list } }
it's not problem t , s, comparable , double.
the reason error map<t, double> not map<t, comparable>.
you'll have widen bit scope of second type-parameter. like:
public static <t, s extends comparable<s>> list<t> function(map<t, s> map) { //implementation } then, you'll able invoke method with:
map<s, double> map = new hashmap<s, double>(); function(map);
Comments
Post a Comment