
[英]ConcurrentModificationException Program in java HashMap
[英]ConcurrentModificationException in HashMap
我正在从用户那里获取保险详细信息,并将其保存在哈希图中。 我有一个名为“保存”的按钮。 因此,仅当用户单击此按钮时,所有保险才应保存在数据库中,因此我将随机生成的ID作为参考,直到将详细信息保存在数据库中。保存到数据库中后,我需要使用密钥作为自动生成的ID更新此哈希图
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
,这会导致异常,因为在迭代Map
时无法修改集合。
相反,您应该使用第二个Map
存储更新的值,并使用Map#putAll
重新同步这两个值,例如...
// Test map full of values...
Map<Integer, String> mapTest = new HashMap<>(25);
for (int index = 0; index < 10; index++) {
mapTest.put(index, Integer.toString(index));
}
// Grab an iterator
Iterator<Map.Entry<Integer, String>> insurances = mapTest.entrySet().iterator();
// Create a temp map for the new values
Map<Integer, String> newValues = new HashMap<>(25);
while(insurances.hasNext()) {
Map.Entry<Integer, String> entry = insurances.next();
int key = entry.getKey();
// Make the comparison about what we want to do, here
// we're removing even keys
if (key % 2 == 0) {
// Remove the old entry
insurances.remove();
// Use the temp map to create a new entry
newValues.put(key * 10, entry.getValue());
}
}
// Merge the results
mapTest.putAll(newValues);
作为一种可能的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.