1

I have a JavaTree ,its all node has a name and assigned value. I want to add these names and values to HashMap. But, I can't take all results to HashMap finally. It take only one value in one time. I used following code.

public HashMap<String, Double> printAll(TreeNode root) {

  HashMap<String, Double> allContainNodes = new HashMap<String, Double>();
  NodeInfor nodeObj = (NodeInfor) ((DefaultMutableTreeNode) root).getUserObject();

  Enumeration children = root.children();

  if (children != null) 
    while (children.hasMoreElements()) {
      printAll((TreeNode) children.nextElement());
    }
  }

  allContainNodes .put(nodeObj.name, nodeObj.specVal);
  return allContainNodes;
}
2
  • Can you show the error message ? Commented Jun 8, 2016 at 14:24
  • Thank you for your reply. It didn't give any error message. But, I can't take all results to HashMap finally. It take only one value in one time. Commented Jun 8, 2016 at 14:33

2 Answers 2

2

You could for example pass the instance of the HashMap to the next level of the iteration, modifying your method like following (only the first run should instanciate it),

public HashMap<String, Double> printAll(TreeNode root, HashMap<String, Double> allContainNodes) {

  if (allContainNodes==null){
   allContainNodes = new HashMap<String, Double>();
  }
  NodeInfor nodeObj = (NodeInfor) ((DefaultMutableTreeNode) root).getUserObject();

  Enumeration children = root.children();

  if (children != null) 
    while (children.hasMoreElements()) {
      printAll((TreeNode) children.nextElement(), allContainNodes );
    }
  }

  allContainNodes.put(nodeObj.name, nodeObj.specVal);
  return allContainNodes;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your reply.
1

You lose the printAll values in your recursive call, try something like

allContainNodes.putAll(printAll((TreeNode) children.nextElement()));

2 Comments

You mean instead of allContainNodes .put(nodeObj.name, nodeObj.specVal); ? It gave an error Exception in thread "main" java.util.NoSuchElementException at java.util.Collections$EmptyEnumeration.nextElement(Unknown Source)
No, i meant instead of printAll((TreeNode) children.nextElement()); in your loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.