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;
}
A. He's just got wildcards everywhere.createAHashtableare capable of handling values ofA<T>ANDA<Float>. This is difficult to model in Java without an additional indirection. Case 2 -- all callers are capable of handling anyA<Number>. If so, the API should returnHashtable<String,A<Number>>. Case 3 -- A caller expects something other thanA<Float>, and dies with a class cast exception at runtime.