Reputation: 741
the code snippet below does not compile; I have a generic class with a Map which maps from a generic key K to Floats. Most of my methods deal with this map in a truly generic way.
Additionally, I want to allow initialising the map with ascending integer values. Clearly, this requires me to constrain the method to K=Integer only. Unfortunately, I get the following error:
The method put(K, Float) in the type Map is not applicable for the arguments (K extends Integer, Float)
Any help here is 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++;
}
}
}
Upvotes: 1
Views: 70
Reputation: 698
Another way as the subclass, is to use a static create method:
class MyClass<K> {
private final Map<K, Float> myMap;
public MyClass() {
myMap = new HashMap<>();
}
public static MyClass<Integer> create(int size) {
MyClass<Integer> result = new MyClass<>();
for(int i = 0; i < size; i++) {
Float rnd = ThreadLocalRandom.current().nextFloat();
result.myMap.put(bar,rnd);
}
return result;
}
}
Upvotes: 1
Reputation: 8168
You can extend your class and specify parameter type for 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 to stay fully generic and also to use it's map with Integer type.
For more about extending generic classes you can read here.
Hope it helps.
Upvotes: 4