【发布时间】:2015-11-20 07:15:07
【问题描述】:
如何使用泛型创建激活键?这段代码甚至无法编译:
/* populate the map with a new value if the key is not in the map */
private <K,V> boolean autoVivify(Map<K,V> map, K key)
{
if (! map.containsKey(key))
{
map.put(key, new V());
return false;
}
return true;
}
【问题讨论】:
-
这似乎可以编译(未测试):
(V)(map.getClass().getTypeParameters()[1].getClass()).newInstance()
标签: java generics dictionary autovivification