java - Constraining method in generic class to specific type -
the code snippet below not compile; have generic class map maps generic key k floats. of methods deal map in generic way.
additionally, want allow initialising map ascending integer values. clearly, requires me constrain method k=integer only. unfortunately, following error:
the method put(k, float) in type map not applicable arguments (k extends integer, float)
any here highly appreciated!
public class myclass<k> { map<k,float> mymap; <k extends integer> myclass(int size){ distribution = new hashmap<k,float>(); integer bar = 0; while(bar<size){ float rnd = threadlocalrandom.current().nextfloat(); mymap.put(bar,rnd); bar++; } } }
you can extend class , specify parameter type base class:
class myclass<k> { map<k,float> mymap; } class derived extends myclass<integer>{ void sparsepdt(int size){ mymap = new hashmap<integer,float>(); integer bar = 0; while(bar<size){ float rnd = threadlocalrandom.current().nextfloat(); mymap.put(bar,rnd); bar++; } } }
it makes class "myclass" available stay generic , use it's map integer type.
more extending generic classes can read here.
hope helps.
Comments
Post a Comment