在Java中使用嵌套MAP结构时出错

时间:2014-06-23 19:18:16

标签: java collections map hashmap

我正在尝试将地图放到另一个地图中,但是当这个地图变得更长时会出错。

地图1

Map<String, String> innerMap = new HashMap<String, String>();

地图2

Map<Map<String,String>, List> outerMap = new HashMap<Map<String,String>, List>();

MAP3

Map<Map<Map<String,String>, List>, List> returnValueMap = new   HashMap<Map<Map<String,String>, List>, List>();

我正在尝试将map1放入map2,然后将map2放入map3,但声明语句会给我一个错误。谁能建议。感谢。

    Map<String, String> innerMap = new HashMap<String, String>(); 
    innerMap.put(key,value); 

    List articleTitleList = new ArrayList(); 
    Map<Map<String,String>, List> outerMap = new HashMap<Map<String,String>, List>();    

    outerMap.put(innerMap,articleTitleList); 
    List articleList = new ArrayList(); 
    Map<Map<Map<String,String>, List>, List> returnValueMap = new HashMap<Map<Map<String,String>, List>, List>(); 
    returnValueMap.put(outerMap,articleList)

2 个答案:

答案 0 :(得分:2)

public static void main(String[] args) {

    Map<String, String> innerMap = new HashMap<String, String>();
    Map<Map<String,String>, List> outerMap = new HashMap<Map<String,String>, List>();
    Map<Map<Map<String,String>, List>, List> returnValueMap = new HashMap<Map<Map<String,String>, List>, List>();

}

这为我编译并运行,检查您是否没有拼写错误或问题。我也非常高度,高度,不建议使用地图作为另一张地图的关键。

答案 1 :(得分:1)

您可以使用 Guava 钻石运算符来避免拼写错误并将其写入两次。例如:

<强>地图1

Map<String, String> innerMap = new HashMap<String, String>();

更改为:

Map<String, String> innerMap = new HashMap<>(); // Diamond operator
Map<String, String> innerMap2 = Maps.newHashMap(); // Using Guava

Map3

Map<Map<Map<String,String>, List>, List> returnValueMap = new   HashMap<Map<Map<String,String>, List>, List>();

更改为

Map<Map<Map<String,String>, List>, List> returnValueMap = new HashMap<>(); // Diamond operator
Map<Map<Map<String,String>, List>, List> returnValueMap2 = Maps.newHashMap(); // Using Guava