我正在尝试使用递归在对象内添加对象。我的对象包含一个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;
}
我的猜测是我在这里的某个地方弄乱了但是我无法弄清楚我在哪里乱搞。提前感谢任何建议或帮助。
我的subChapters类:
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;
}
答案 0 :(得分:2)
你正在做的是subChapters.setSubChapters,我认为你要做的是 subChapters.addSubChapters。
它使用字符串的原因是因为你使用+ =来添加 旧字符串的新字符串。执行setSubChapters与使用=和字符串相同。
addSubChapters是一个应该在subChapters类中添加一些ArrayList变量的方法。