是否可以将两个通配符类型声明为相同类型?

Jap*_* D. 4 java generics

我想创建一个映射,从(a)类类型到(b)long(定义类类型的对象的标识符)到(c)对象本身.

我有以下内容:

 protected HashMap<Class<?>, HashMap<Long, ?>> obj = new HashMap<Class<?>, HashMap<Long, ?>>();
Run Code Online (Sandbox Code Playgroud)

有可能以某种方式表示第一个?必须与第二个类型相同?吗?我希望这样的事情,但这是不可能的:

protected <T> HashMap<Class<T>, HashMap<Long, T>> obj = new HashMap<Class<T>, HashMap<Long, T>>();
Run Code Online (Sandbox Code Playgroud)

mil*_*ose 5

作为替代方案,您可以使用少量非类型安全的代码,这些代码以强制执行约束的方式封装:

class Cache {
    private Map<Class<?>, Map<Long, ?>> items = new HashMap<Class<?>, Map<Long, ?>>();

    private <T> Map<Long, T> getItems(Class<T> type) {
        @SuppressWarnings("unchecked")
        Map<Long, T> result = (Map<Long, T>) items.get(type);
        if (result == null) {
            result = new HashMap<Long, T>();
            items.put(type, result);
        }
        return (Map<Long, T>) result;
    }

    public <T> void addItem(Class<T> type, Long id, T item) {
        getItems(type).put(id, item);
    }

    public <T> T getItem(Class<T> type, Long id) {
        return type.cast(getItems(type).get(id));
    }
}
Run Code Online (Sandbox Code Playgroud)

type.cast()getItem()不需要编译器不会抱怨,但它会帮助赶上了错误的类型进入缓存早期的对象.