【发布时间】:2011-07-16 12:01:26
【问题描述】:
这是一些无法编译的代码。我想在 typeMap 中保存任意对 Class<?>(键)和 Map<Long, ObjectDescriptors<?>>(值);
从其他方法中,我想使用具有具体类型的值映射之一,但算法应该是通用的。我编写了getIdentityMap() 方法来提供具有具体但通用类型的地图。
我必须如何修改代码以在泛型的同时进行编译?
提前致谢。
private final Map<Class<?>, Map<Long, ObjectDescriptor<?>>> typeMap = new HashMap<Class<?>, Map<Long,ObjectDescriptor<?>>();
private <T> Map<Long, ObjectDescriptor<T>> getIdentityMap(Class<T> type) {
Map<Long, ObjectDescriptor<T>> identityMap = typeMap.get(type);
if (identityMap == null) {
identityMap = new HashMap<Long, ObjectDescriptor<T>>();
typeMap.put(type, identityMap);
}
return identityMap;
}
编辑:这是编译器错误:
- 在线:
Map<Long, ObjectDescriptor<OBJECT_TYPE>> identityMap = typeMap.get(type);- 编译器错误:
Type mismatch: cannot convert from Map<Long,ObjectDescriptor<Object>> to Map<Long,ObjectDescriptor<OBJECT_TYPE>>
- 编译器错误:
- 在线:
typeMap.put(type, identityMap);- 编译器错误:
The method put(Class<?>, Map<Long,ObjectDescriptor<Object>>) in the type Map<Class<?>,Map<Long,ObjectDescriptor<Object>>> is not applicable for the arguments (Class<OBJECT_TYPE>, Map<Long,ObjectDescriptor<OBJECT_TYPE>>)
- 编译器错误:
编辑:将地图属性的通用类型编辑为?
【问题讨论】:
-
请不要使用
,而只使用 。如果您不遵守约定,阅读起来会很混乱。 -
请同时包含编译错误。
-
基本问题是不能用类型变量实例化泛型类:
new Something<T>();是不可能的。这是由于泛型在 Java 中实现的方式(擦除)。有关解决方法,请参阅this post。可能有更好的帖子更接近您的问题,但我现在必须运行...... -
@toto: 为什么
new Something<T>不可能?List<T> t = new ArrayList<T>()非常有编译能力。当然,如果你说new T(),那么是的,那是不可能的。 -
@Sanjay 谢谢。相当棘手:
new ArrayList<?>()无效,但new ArrayList<ArrayList<?>>()是允许的。
标签: java generics map wildcard