views:

77

answers:

2

Suppose I want to write a function, which will create a HashMap from some specified type T to String, for example, a HashMap from Integer to String as follows:

HashMap<Integer, String> myHashMay = new HashMap<Integer, String>();

I want to have flexibilty to specify the type T. So I write a function as:

void foo(Class<?> myClass) {
    HashMap<myClass, String> myHashMay = new HashMap<myClass, String>();
    .......
}

so that if I invoke foo(Integer.class), a HashMap from Integer to String will be created inside this function. Apparently the above foo function does not even compile. Could anybody give me some hints on how to write such a function correctly with the given function signature.

Thanks,

+2  A: 
<T> void foo(Class<T> myClass) {
    HashMap<T, String> myHashMay = new HashMap<T, String>();
    ...
}

EDIT: However, method with such a signature doesn't seem to be very useful, because T is used only for type checking at compile time. I can imagine only the single scenario when it can be used:

<T> void foo(Class<T> myClass) {
    HashMap<T, String> myHashMay = new HashMap<T, String>();
    ...
    try {
        T key = myClass.newInstance();
        myHashMay.put(key, "Value");
    } catch (Exception ex) { ... }
    ...
}
axtavt
+1  A: 

This function creates a map like you are trying to do:

public <KeyType> Map<KeyType,String> createMapWithKeyType(Class<KeyType> keyType)
{
    return new HashMap<KeyType, String>();
}

Note: pay attention to the comment by matt b, he makes a good point.

instanceofTom
Thank you guys for both the answers and comments. They are very helpful. Since I am using some third party code, I have to hack this way in order to get my code work.
RecSys2009