Pergunta

I have this code:

import java.util.*;
public class StorageCenter {
    protected HashMap<Class<?>,HashMap<String,?>> storage;
    public <T> void put(Class<T> c,String key, T value){
        if(!storage.containsKey(c)){
            storage.put(c, new HashMap<String,T>());
        }
        storage.get(c).put(key, value);
    }
    @SuppressWarnings("unchecked")
    public<T> T get(Class<T> c,String key){
        return (T) storage.get(c).get(key);
    }
}

I expect that these methods should work, allowing me to have a "double" hash map, where the first layer is a Class object and the second layer is a HashMap of that type of object.

However this code does not work, I get a compile error when I try to use it:

storage.get(c).put(key, value);

Why is this not legal code?

Foi útil?

Solução

? does not mean 'Any Type' it means 'Unknown Type.' Therefore it is not legal to add anything to that map, because you don't know what types are legal to add. If you want to be able to add anything, the type parameter is Object.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top