使用 java 将所有 Java 树节点及其自身的值添加到 HashMap
Add all Java tree nodes and its own value to HashMap using java
我有一个 JavaTree,它的所有节点都有一个名称和指定的值。我想将这些名称和值添加到 HashMap。但是,我最终无法将所有结果都带到 HashMap 中。一次只取一个值。我使用了以下代码。
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;
}
您在递归调用中丢失了 printAll 值,请尝试
allContainNodes.putAll(printAll((TreeNode) children.nextElement()));
例如,您可以将 HashMap 的实例传递到迭代的下一级,像下面这样修改您的方法(只有第一个 运行 应该实例化它),
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;
}
我有一个 JavaTree,它的所有节点都有一个名称和指定的值。我想将这些名称和值添加到 HashMap。但是,我最终无法将所有结果都带到 HashMap 中。一次只取一个值。我使用了以下代码。
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;
}
您在递归调用中丢失了 printAll 值,请尝试
allContainNodes.putAll(printAll((TreeNode) children.nextElement()));
例如,您可以将 HashMap 的实例传递到迭代的下一级,像下面这样修改您的方法(只有第一个 运行 应该实例化它),
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;
}