I have a class A like this:
public class A<T extends Number>
{
....
}
In another class I have this method:
public Hashtable<String, A> createAHashtable()
{
Hashtable<String, A> hTable = new Hashtable<String, A>();
return hTable;
}
There is a warning for parameter A because it is generic class. So should I do this:
public Hashtable<String, A <?>> createAHashtable()
{
Hashtable<String, A<?>> hTable = new Hashtable<String, A<?>>();
return hTable;
}
or do this:
public Hashtable<String, A <? extends Number>> createAHashtable()
{
Hashtable<String, A<? extends Number> hTable = new Hashtable<String, A<? extends Number>();
return hTable;
}
or ….???
EDIT:
Tried this (as suggested by Dilum)
public <T extends Number> Hashtable<String, A<T>> createAHashtable()
{
Hashtable<String, A<T>> hTable =
new Hashtable<String, A<T>>();
A<Float> constraint = new A<Float>();
hTable.put("test", constraint);
return hTable;
}
But it is invalid to “put” my Float A.
Maybe the wildcard is the way to go.
EDIT 2:
Based on Dilum’s suggestion, the following code (cast to A when put a Float A into the Hashtable) has no error but warning it is unsafe cast. Why we need the cast?
public <T extends Number> Hashtable<String, A<T>> createAHashtable()
{
Hashtable<String, A<T>> hTable =
new Hashtable<String, A<T>>();
A<Float> constraint = new A<Float>();
hTable.put("test", (A<T>)constraint);
return hTable;
}
Try this:
Say you did want to pre-fill with a key-value pair, try: