Problems retrieving objects from HashMap from HashMaps

I am writing code that repeats recursively through an XML file and populates the HashMap from HashMaps. I was able to fill the hash map and it looks fine. However, when I run this command

 System.out.println(map.containsKey("Mary"));

Its always a lie. Not really sure why it always returns false. I also posted my recursive code and the contents of the hash map after

map.toString() 
map is { Mary
    ={24
        ={established
            ={western
                ={Profile=m}}, torn-down
            ={western
                ={Profile=b}, eastern
                ={Profile=m}}}, 44
        ={established
            ={western
                ={Profile=g}, eastern
                ={Profile=s}}, torn-down
            ={western
                ={Profile=j}, western
                ={Profile=f}}}}, Martha
    ={24
        ={established
            ={western
                ={Profile=a}}, torn-down
            ={western
                ={Profile=b}, eastern
                ={Profile=n}}}, 44
        ={established
            ={western
                ={Profile=s}, eastern
                ={Profile=j}}, torn-down
            ={western
                ={Profile=k}, eastern
                ={Profile=g}}}}}

Recursive code:

NodeList l = doc.getElementsByTagName("Branches");
        Node n = l.item(0);
        map = new HashMap();
        recurse(n, map);

private void recurse(Node n, HashMap map){
if (n.hasChildNodes()){
    NodeList nl = n.getChildNodes();

    for(int i= 0; i< nl.getLength(); i++){
        Node node = nl.item(i);

        if(node.getNodeType() == Node.ELEMENT_NODE){
            if (!node.getNodeName().equals("Profile") ){

                map.put(node.getFirstChild().getNodeValue(), new HashMap());

                recurse(node, (HashMap)map.get(node.getFirstChild().getNodeValue()));
            }
            else {

                map.put("Profile", node.getFirstChild().getNodeValue());
                }


            }
        }       
    }

}   

Thank!

+3
source share
1 answer

As requested by OP- and since the discussion in the comments resolved his problem - I wrap it as an answer - for future readers:

You must first check if your keys are valid String. You can do this by adding the line:

System.out.println(map.keySet().iterator().next().getClass());

, , , String s, , , , :

String s = (String)map.keySet().iterator().next(); 
System.out.println("val=" + s + " length=" + s.length());

- , .

[ , OP], XML, .

, - , , , !
, , .

+2

All Articles