1

如何在此地图中放置值?

public static Map<String, TreeMap<String, SomeClass>> myMap=Collections.synchronizedMap(new TreeMap<String, TreeMap<String,SomeClass>>());
4

3 回答 3

1

首先,您需要确保“内部映射”存在,然后您可以将值放入其中:

String outerKey = "exampleKey1";
String innerKey = "exampleKey2";
SomeClass innerValue = new SomeClass();

TreeMap<String, SomeClass> innerMap = myMap.get(outerKey);
if (innerMap == null) {
  innerMap = Collections.synchronizedMap(new TreeMap<String, SomeClass>());
  myMap.put(outerKey, innerMap);
}
innerMap.put(innerKey, innerValue);

您还应该考虑将类型更改为:

public static Map<String, SortedMap<String, SomeClass>> myMap = ...
//                        ^^^^^^^^^

或仅Map取决于您是否需要 sorted 属性。

于 2013-06-17T20:44:54.510 回答
1
TreeMap<String, SomeClass> map = myMap.get(key1)
if(map == null) {
  map = Collections.synchronizedMap(new TreeMap<String, SomeClass>());
  myMap.put(key1, map);
}
map.put(key2, value);
于 2013-06-17T20:44:55.277 回答
0
TreeMap<String, SomeClass> value = new TreeMap<String, SomeClass>();
myMap.put("key", value);
于 2013-06-17T20:45:17.033 回答