我有地图
Map<String, Map<String,Integer>> outerMap = new HashMap<String, Map<String, Integer>>();
我想把一些价值放在内部地图上。这样做对吗?还是可以做得更好?
class SampleMap {
Map<String, Map<String, Integer>> outerMap = new HashMap<String, Map<String, Integer>>();
public void add(String outerKey, String innerKey, Integer value) {
Map<String, Integer> tempMap = new HashMap<String, Integer>();
if (outerMap.size() > 0)
tempMap = outerMap.get(outerKey);
tempMap.put(innerKey, value);
outerMap.put(key, tempMap);
}
}
发布于 2014-05-30 12:19:26
您可以通过避免创建新的内部映射来改进代码,直到您知道必须创建它时为止。
此外,如果您知道内部map实例来自外部映射,则无需花费时间将其放回原来的位置。
public void add(String outerKey, String innerKey, Integer value) {
Map<String, Integer> tempMap
if (outerMap.containsKey(outerKey)) {
tempMap = outerMap.get(outerKey);
} else {
tempMap = new HashMap<String, Integer>();
outerMap.put(outerKey, tempMap);
}
tempMap.put(innerKey, value);
}
发布于 2014-05-30 12:27:31
从技术上讲,您的代码中没有什么问题(除了dasblinkenlight建议的一个小改进),但是地图地图是否符合您的实际需要呢?
如果您想用两个键来读取/写入值,最好是从一对两个键(可以使用MultiKey或配对实现)或另一个数据结构创建映射(详细信息,请参阅此注释https://stackoverflow.com/a/3093993/554281)。
https://stackoverflow.com/questions/23954422
复制相似问题