我有一个场景,我从查询获得的结果集中迭代一组行
-->查询
System.out.println("---Iterating Events---");
while (rs.next()) {
startOfMethod(rs);
}
startOfMethod(ResultSet result)
{
HashMap hmap;
String applicationGroupMap;
String description;
description = result.getString("description"); //description is an XML string
hmap = new XMLRead().xmlDataOutput(description); //This is a separate class which returns a hashmap
applicationGroupMap = (String) hmap.get("Attribute.applicationGroupMap");
}
问题是,有时当它从第一行迭代到第二行并且第二行没有“Attribute.applicationGroupMap”时,它会保留旧值。
谁能告诉我如何在每次迭代时刷新 hmap?
返回 Hmap 的代码:-
try {
Document doc = convertToDocument(xmlStr);
String hashKey = "";
String hashValue = "";
NodeList listOfKeyValues = doc.getElementsByTagName("k");
for (int s = 0; s < listOfKeyValues.getLength(); s++) {
Node firstNode = listOfKeyValues.item(s);
if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstElement = (Element) firstNode;
NodeList keyList = firstElement.getChildNodes();
hashKey = ((Node) keyList.item(0)).getNodeValue().trim();
NodeList listOfvalues = doc.getElementsByTagName("v");
Node secondNode = listOfvalues.item(s);
Element valueElement = (Element) secondNode;
NodeList valueList = valueElement.getChildNodes();
if (valueList.getLength() != 0) {
hashValue = ((Node) valueList.item(0)).getNodeValue();
} else {
hashValue = "";
}
hsMap.put(hashKey, hashValue);
}
}
} catch (Throwable t) {
t.printStackTrace();
}
return hsMap;
}
最佳答案
您的 hmap
变量甚至不应该是成员变量,更不用说静态变量了。它应该是方法本地的,并且该方法应该在每次调用时分配一个新的。
更准确的标题版本是“旧的 HashMap
持有旧值”。
关于java - HashMap 保存旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9971476/