鉴于:
Object nestKey;
Object nestedKey;
Object nestedValue;
Map<T,Map<T,T>> nest;
Map<T,T> nested;
如何将映射添加到嵌套 where:
nest.containsKey(nestKey) == true;
?
或者是否有一个更有效的现有馆藏库?
鉴于:
Object nestKey;
Object nestedKey;
Object nestedValue;
Map<T,Map<T,T>> nest;
Map<T,T> nested;
如何将映射添加到嵌套 where:
nest.containsKey(nestKey) == true;
?
或者是否有一个更有效的现有馆藏库?
这是一个相当普遍的习语:
您的意思是类似于以下通用方法?
static <U,V,W> W putNestedEntry(
Map<U,Map<V,W>> nest,
U nestKey,
V nestedKey,
W nestedValue)
{
Map<V,W> nested = nest.get(nestKey);
if (nested == null)
{
nested = new HashMap<V,W>();
nest.put(nestKey, nested);
}
return nested.put(nestedKey, nestedValue);
}
不明白你的意思。我认为您想添加到嵌套地图中,如下所示:
nest.get(nestKey).put(nestedKey, nestedValue);
这是不可能的,因为外部地图上的 get 返回类型为 的地图Map<?, ?>
。您不能对其调用 put 方法。无界通配符 '?' 如果您不知道集合内容的类型但想将它们视为对象,则应使用。如果你想读取和修改内容,并且 Map 有异构对象,你可以使用 raw 类型。那是这样的:
Map<?, Map> nest;
最好的方法当然是(如果可能的话),使用同质 Map 并指定其类型。例如。Map<String, String>
试试这个
if (nest.containsKey(nestKey)) { ((Map) nest.get(nestKey)).put(nestedKey, nestedValue); }