如何使静态递归方法返回HashMap?

时间:2012-06-21 06:33:47

标签: java android recursion

我正在创建一个帮助器方法的过程,它允许我遍历XML文档并将每个元素放在数据HashMap中然后返回它。这是我一直在研究的方法:

private static HashMap<String, String> traverseNodes( Node n, HashMap<String,String> data ) 
{
    NodeList children = n.getChildNodes();
    if( children != null ) {
      for( int i = 0; i < children.getLength(); i++ ) {
        Node childNode = children.item( i );

        String nodeName = childNode.getNodeName();
        if(childNode instanceof Element)
        {
            data.put(nodeName, getStringByTag(nodeName, (Element)childNode));
            Log.d("traversal", childNode.getNodeName() + " was saved in hashmap");
        }


        else
            Log.d("traversal", childNode.getNodeName() + " Is not an Element type");

        System.out.println( "node name = " + childNode.getNodeName() );
        traverseNodes( childNode, data );
      }
    }

    return data;

}

我尝试运行该示例,虽然我收到消息说“childNode.getNodeName()+”已保存在hashmap中。但返回的HashMap为空。

我做错了什么?

编辑!奖金问题:我编辑了代码以反映建议的更改。但是,似乎该方法本身不保存我的XML文档的值。方法中的逻辑有问题吗?

4 个答案:

答案 0 :(得分:3)

您正在为每次通话创建新地图。您需要将现有的地图传递给递归调用。它应该看起来像这样:

private static Map<String, String> traverseNodes(Node n) {
    Map<String, String> map = new HashMap<String, String>();
    traverseNodesRecurse(n, map);
    return map;
}

private static void traverseNodesRecurse(Node n, Map<String, String> map) {
    // Logic as per question
    // Recursive call (in the loop, etc)
    traverseNodes(childNode, map);

    // No need for a return statement
}

答案 1 :(得分:0)

我会说保留HashMap在方法之外并将其作为参数传递 -

private static HashMap<String, String> traverseNodes( Node n, HashMap<String, String> data  ) 

答案 2 :(得分:0)

我认为你需要类似的东西

private static HashMap<String, String> traverseNodes( Node n ) {
    HashMap<String, String> data = new HashMap<String, String>();
    traverseNodes( n, data );
    return data;
}

private static void traverseNodes( Node n, HashMap<String, String> data ) {
    // Here is your recursive code that do data.put(key, value)
}

答案 3 :(得分:0)

private static HashMap<String, String> data = new HashMap<String, String>();

private static traverseNodes( Node n) 
{
    NodeList children = n.getChildNodes();
    if( children != null ) {
      for( int i = 0; i < children.getLength(); i++ ) {


        Node childNode = children.item( i );

        if(childNode instanceof Element)
        {

            String nodeName = childNode.getNodeName();
            data.put(nodeName, getStringByTag(nodeName, (Element)childNode));
            Log.d("traversal", childNode.getNodeName() + " was saved in hashmap");
        }


        else
            Log.d("traversal", childNode.getNodeName() + " Is not an Element type");

        System.out.println( "node name = " + childNode.getNodeName() );
        traverseNodes( childNode);
      }
    }

    return data;

}