문제

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?

도움이 되었습니까?

해결책

? 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top