0
NodeList nList2 = doc.getElementsByTagName("dep");
Map<String, List<Map<String, String>>> depMap = new HashMap<String, List<Map<String, String>>>();
for (int temp = 0; temp < nList2.getLength(); temp++) {
  Element el = (Element)nList2.item(temp);
  String type=el.getAttribute("type");
  Node nNode = nList2.item(temp);
  if (nNode.getNodeType() == Node.ELEMENT_NODE) {
    Element eElement = (Element) nNode;
    List<Map<String,String>> depList = new ArrayList<Map<String,String>>();
    String governor = getTagValue("governor", eElement);
    String dependent = getTagValue("dependent", eElement);
    Map<String, String> govdepmap = new HashMap<String, String>();
    govdepmap.put(governor, dependent);
    depList.add(govdepmap);
    List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
    flist.add(govdepmap);
    depMap.put(type, flist);
  }
}

我写了这段代码,但问题是每当循环运行时,它都会替换已经存储在 depMap 中的 List。我希望它应该在从 depMap 检索到的 List 中附加新 Map 而不是替换它。

4

3 回答 3

3

因此,您不需要在每次迭代中创建新列表,而是需要从地图和add()项目中获取列表到该列表

改变

List<Map<String,String>> flist = new ArrayList<Map<String,String>>();

List<Map<String,String>> flist = depMap.get(type);
if(flist == null){
 List<Map<String,String>> flist = new ArrayList<Map<String,String>>();
}
于 2012-07-05T06:29:35.013 回答
0

将 , 的初始化移到flistforgovdepmap循环depList之外。

于 2012-07-05T06:32:41.223 回答
0

只需将您的代码更改为以下代码。

    NodeList nList2 = doc.getElementsByTagName("dep");
    Map<String, List<Map<String, String>>> depMap = new HashMap<String, List<Map<String, String>>>();
    List<Map<String,String>> flist = null;
    for (int temp = 0; temp < nList2.getLength(); temp++) {
      Element el = (Element)nList2.item(temp);
      String type=el.getAttribute("type");
      Node nNode = nList2.item(temp);
      if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        List<Map<String,String>> depList = new ArrayList<Map<String,String>>();
        String governor = getTagValue("governor", eElement);
        String dependent = getTagValue("dependent", eElement);
        Map<String, String> govdepmap = new HashMap<String, String>();
        govdepmap.put(governor, dependent);
        depList.add(govdepmap);
        if(flist == null){
            flist = new ArrayList<Map<String,String>>();
        }
        flist.add(govdepmap);
        depMap.put(type, depList);
      }
    }
于 2012-07-05T06:39:04.337 回答