In this Example we are going to understand the exceptions while iterating if we remove any key value of Hashkey.
Error Message :
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)
at com.si.hashmap.HashMapOperations.main(HashMapOperations.java:17)
Error Description :
package com.si.hashmap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapOperations {
public static void main(String[] args) {
Map<String,Integer> intMap = new HashMap<String,Integer>();
intMap.put("First", 568);
intMap.put("Second", 123);
intMap.put("third", 52);
Set<String> set = intMap.keySet();
for(String key : set) {
System.out.println(intMap.get(key));
if(key.equals("Second")) {
intMap.remove(key);
}
}
}
}
In the above example ,the red background color line is giving the exception.
When we are iterating the hashmap ,the remove() will change the hashmap only so this give inconsistency ,sowe will get this kind of exceptions.
Solution:
We can use Iterator for this modifications on the Hashmap while doing some operation like Iteration on the HashMap. Iterator have some variable to check the HashMap changes for every next() value. So its Safe while iteration.
package com.si.hashmap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapOperations {
public static void main(String[] args) {
Map<String,Integer> intMap = new HashMap<String,Integer>();
intMap.put("First", 568);
intMap.put("Second", 123);
intMap.put("third", 52);
System.out.println(intMap);
Iterator<String> it = intMap.keySet().iterator();
while(it.hasNext()) {
String val = it.next();
if((val).contains("Second")) {
it.remove();
}
}
System.out.println(intMap);
}
}
Output:
{Second=123, third=52, First=568}
{third=52, First=568}
Post a comment
Please share your valuable feedback and share this article in social media.