【发布时间】:2014-10-13 17:28:29
【问题描述】:
我有一个 HashMap,它接受一个字符串作为键,一个元素的数组列表作为值。
我为此写的逻辑是: 列表 lsChildLine = new ArrayList();
NodeList nlBook = doc.getElementsByTagName("Book");
for(int cnt=0; cnt < nlBook.getLength() ; cnt++){
Element elBook = (Element) nlBook.item(cnt);
Element childLine = Util.getChildElement(elBook , "ChildLine");
Element parentLine = Util.getChildElement(elBook , "ParentLine");
String parentLineNo = parentLine.getAttribute("LineNo");
if(!mapParentAndChildLines.containsKey(parentLineNo)){
lsChildLine.add(childLine);
mapParentAndChildLines.put((parentLineNo), lsChildLine);
}else{
lsChildLine = mapParentAndChildLines.get(parentLineNo);
lsChildLine.add(childLine);
mapParentAndChildLines.put((parentLineNo), lsChildLine);
}
}
现在我必须根据每个键的列表大小做一些逻辑。
当我是循环遍历的 xml 时,这很好用:
<BookShelf>
<Book Name="ABC">
<ParentLine LineNo="1">
<ChildLine LineNo="2">
</Book>
</BookShelf>
但这不起作用,xml就像:
<BookShelf>
<Book Name="ABC">
<ParentLine LineNo="1">
<ChildLine LineNo="2">
</Book>
<Book Name="ABC">
<ParentLine LineNo="3">
<ChildLine LineNo="4">
</Book>
</BookShelf>
在这种情况下,第一次迭代循环时,地图中不存在lineNo,因此将元素ChildLine添加到列表中。
当第二次迭代循环时,该键也不存在于映射中,因此它进入了 If 块。现在列表对象已经有了循环中前一个元素的 ChildLine,并且对应于新键的 childLine 被插入到同一个循环中,结果列表大小变成了 2,而理想情况下它应该是 1。
我想不出一个合适的逻辑来避免这种情况,尽管我觉得这与将列表贴在正确的位置有关。
对此有什么帮助吗?
【问题讨论】:
标签: java dom for-loop arraylist hashmap