是否有可能声明两个通配符类型是相同的类型? [英] Is it possible to declare two wildcard types to be of same type?
问题描述
我想创建一个从(a)类型到(b)long(定义的类类型的对象的标识符)到(c)该对象本身的映射。
I want to create a mapping from (a) class type to (b) long (the identifier of the object of the defined class type) to (c) the object itself.
我有以下内容:
I have the following:
protected HashMap<Class<?>, HashMap<Long, ?>> obj = new HashMap<Class<?>, HashMap<Long, ?>>();
有可能以某种方式表示第一个?
必须与第二个?
相同。我会期待这样的事情,但这是不可能的:
Is it possible to somehow denote that the first ?
must be of the same type than the second ?
? I would expect something like this, but this is ofcourse not possible:
protected <T> HashMap<Class<T>, HashMap<Long, T>> obj = new HashMap<Class<T>, HashMap<Long, T>>();
推荐答案
作为替代方案,您可以使用少量非类型安全的代码封装在一个强制你的约束的方式:
As an alternative, you could use a small amount of not-type-safe code encapsulated in a way that enforces your constraint:
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));
}
}
type.cast ) in
getItem()
对编译器来说不是必要的,但它可以帮助捕获错误类型的对象进入尽早缓存。
The type.cast()
in getItem()
isn't necessary for the compiler to not complain, but it would help catch an object of the wrong type getting into the cache early.
这篇关于是否有可能声明两个通配符类型是相同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!