【发布时间】:2015-09-23 04:23:52
【问题描述】:
我从用户那里获取保险详细信息并将它们保存在哈希图中。 我有一个叫做保存的按钮。因此,只有当用户单击此按钮时,所有保险都应保存在数据库中 所以我将随机生成的 id 作为参考,直到我将详细信息保存在数据库中 保存到数据库后,我需要使用键作为自动生成的 id 来更新这个 hashmap
public void saveInformationInDatabase(int patientId)
{
// getAllInsurances returns HashMapn<Integer, HashMap<Integer, InsuranceInformation>>
Iterator<Map.Entry<Integer, InsuranceInformation>> insurances = getAllInsurances().get(patientId).entrySet().iterator();
while(insurances.hasNext())
{
InsuranceInformation insuranceInformation = insurances.next().getValue();
if (insuranceInformation.getStatus() == Status.OLD)
continue;
else if (insuranceInformation.getStatus() == Status.NEW)
{
// Saving the Information in database, and returning auto generated ID
int licId = saveInformation(insuranceInformation);
// So, i need to update insuranceInformation with autogenerated ID
// Because previous id is randomly generated number
insuranceInformation.setLicID(licId);
insuranceInformation.setStatus(InsuranceObject.Status.OLD);
// Below line gives me ConcurrentModificationException
getAllInsurances().get(patientId).put(licId, insuranceInformation); // Storing the updated information with newly generated id as key, in hashmap
insurances.remove(); // and here, removing the old hashmap entry
}
}
}
【问题讨论】:
-
有什么问题?这段代码是否在外循环中?
-
这个
getAllInsurances().get(patientId).put(licId, insuranceInformation);会给你带来麻烦。使用临时的Map存储新值,然后使用Map#putAll同步回原始值 -
@MadProgrammer 非常感谢。现在,如果我使用第二个 Hashmap,它可以正常工作
标签: java iterator hashmap concurrentmodification