我正在尝试使用递归在对象中添加一个对象。我的对象包含一个 arrayList,我正在尝试将我的对象添加到此 arrayList。但是我的对象没有添加新对象,而是被替换了。
我的代码正在执行此操作:这是完成添加对象的逻辑的地方。但它正在被替换。
private ArrayList<SubChapters> recursiveSubChapters(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> linkedHashMap, Boolean isSubTree){
SubChapters subChapters = new Subchapters();
ArrayList<SubChapters> alchildUnits = new ArrayList<SubChapters>();
final String chapterId = linkedHashMap.get(tree.getUnitID()).get("unit_num");
final String chapterName= linkedHashMap.get(tree.getUnitID()).get("unit_name");
if (!isSubTree) {
subChapters.set(chapterId);
subChapters.setTreeName(chapterName);
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
subChapters.hasSubUnits(true);
for (ReportingTree subTree: branches) {
subChapters.setSubChapters(recursiveSubChapters(subTree, linkedHashMap, false));
//This is where the logic of adding an object is being done. But it is being replaced instead.
}
alchildUnits.add(subChapters);
}
return alchildUnits;
}
我的猜测是我在这里循环的某个地方搞砸了,但我无法弄清楚我搞砸了哪里。在此先感谢您的任何建议或帮助。
我的子章节类:
public String subChapterID;
public String subChapterName;
public boolean isSubTree= false;
public ArrayList<SubChapters> subChapters;
and getters and setters.
我编写了相同的解决方案以返回字符串并在 jsp 上查看订单。它工作得很好。我无法在此处对我的问题应用相同的方法。
private String recursive(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> listUnitInfo, boolean isTop) {
final String unitID = tree.getUnitID();
final HashMap<String, String> unit = listUnitInfo.get(unitID);
String output = "";
if (!isTop) {
output += "<li><a href=\"./Display.do?unit=" + unitID + "\">" + unit.get("unit_num") + "/" + unit.get("unit_name") + "</a>";
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
if (isTop) {
output += "<li><a href=\"./Display.do?unit=" + unitID + "\">" + unit.get("unit_num") + "/" + unit.get("unit_name") + "</a>";
}
output += "<ul>\n";
for (ReportingTree subTree : branches) {
output += recursive(subTree, listUnitInfo, false);
}
output += "</ul>";
} else {
if (isTop) {
output += "<li>No units match your criteria.";
}
}
output += "</li>\n";
return output;
}
最佳答案
你正在做的是 subChapters.setSubChapters,我认为你正在尝试做的是 subChapters.addSubChapters.
它与字符串一起使用的原因是因为您使用 += 添加 新字符串到旧字符串。执行 setSubChapters 与对字符串使用 = 相同。
addSubChapters 将是一个方法,它应该向 subChapters 类中的 ArrayList 变量添加一些内容。
关于java递归: object is replaced rather than adding a new one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26330745/