嵌套循环在运行时创建重复条目,找不到问题?

时间:2016-08-03 13:06:45

标签: java

当代码运行时,嵌套循环导致它偶尔为系统创建重复条目,我花了一段时间来查看这个,但仍然无法找到导致这种情况的原因,非常感谢任何帮助?

for(int i = 0; i < subWorkItemElement.getChildNodes().getLength(); i++) {
    Boolean test = false;
    WorkItemCommon existingChild = null;
    String summary = null;
    if(subWorkItemElement.getChildNodes().item(i).getNodeName().equals("workitem")) {
        // We know it's a work item - but is it in the existing list?
        Element childWorkItem = (Element) subWorkItemElement.getChildNodes().item(i);
        for(int j = 0; j < subWorkItemElement.getChildNodes().getLength(); j++) {
            if(childWorkItem.getChildNodes().item(j) instanceof Element) {
                if(((Element)childWorkItem.getChildNodes().item(j)).getNodeName().equals("details")) {
                    summary = ((Element) childWorkItem.getChildNodes().item(j)).getElementsByTagName("summary")
                            .item(0).getTextContent();

                    for(String k : userInfoHashMap.keySet()) {
                        summary = summary.replace("${" + k + "}", userInfoHashMap.get(k));
                    }

                    if(childHashTable.containsKey(summary)) {
                        test = true;
                        existingChild = childHashTable.get(summary);
                        IWorkItem workItem = existingChild.getWorkItem();
                        System.out.println("INFO: The task with summary \"" + summary + "\" already exists. Skipping creation.");
                        System.out.println("this task is work item: " + workItem.getId());
                        //either check the tasks in the xml for updated details and then modify the existing workitem
                        //or just modify the work item without checking for updates
                        makeChildTask(childWorkItem, existingChild, childHashTable, userInfoHashMap, workItemHashMap, rtc, false);

                        break;
                    }
                }
            }
        }

        if(!test) {
            System.out.println("INFO: The task with summary " + summary + " does not currently exist. Creating.");
            makeChildTask(childWorkItem, thisItem, childHashTable, userInfoHashMap, workItemHashMap, rtc, true);
        } else makeFromExistingChildTask(childWorkItem, existingChild, userInfoHashMap, workItemHashMap, rtc);
    }
}

1 个答案:

答案 0 :(得分:0)

在迭代子列表时,您可能(不确定makeChildTask()做什么)更改XML结构。虽然不一定不正确,但这可能意味着您在处理列表时会插入条目。由于您每次都调用subWorkItemElement.getChildNodes().getLength()而不是缓存它,这可能会导致循环迭代之间的长度发生变化。