Iterating over a list of user defined class using Iterator class of enhanced for loop gives java.util.ConcurrentModificationException exception but when using the traditional for loop it runs just fine.
Actually I am trying to implement my own hashmap using Java. Below is the perfectly fine working code when I am using indexed for loop:
class MyHashMap {
public final int MAX_VALUE = 1009; // any big prime number
LinkedList<Node> buckets[];
public MyHashMap() {
buckets = new LinkedList[MAX_VALUE];
for (int i = 0;i<buckets.length;i++)
buckets[i] = new LinkedList<Node>();
}
public void put(int key, int value) {
int index = key % MAX_VALUE;
LinkedList<Node> list = buckets[index];
if (get(key) != -1) remove(key); // if the key is available then remove it // same as update
Node entry = new Node(key, value); //otherwise
list.add(entry);
}
public int get(int key) {
int index = key % MAX_VALUE;
List<Node> list = buckets[index];
if(list==null)return -1;
for(Node n : list){
if(n.key == key)return n.val;
}
return -1;
}
public void remove(int key) {
int index = key % MAX_VALUE;
LinkedList<Node> list = buckets[index];
if(list == null)return;
** //synchronized(this){
for(int i=0;i<list.size();i++){
Node n = list.get(i);
if(n.key == key){
list.remove(n);
break;
}**
}
//}
}
}
class Node{
public int key;
public int val;
public Node(int key, int val){
this.key=key;
this.val=val;
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/
I also tried using the enhanced loop inside a synchronized block to no avail.
I have 3 questions for this behaviour:
- Why does the traditional loop works and enhanced loop and iterator does'nt?
- What exactly does the java.util.ConcurrentModificationException exception signify?
- Why does using the enhanced for loop inside the synchronized block (to ensure the loop iteration is locked for a single thread at a time) not help with this java.util.ConcurrentModificationException exception?
- I am trying to implement my own hashmap using Java.
- I tried using iterator in place of enhanced for loop but it does'nt works.
- I also tried putting the enhanced for loop inside a synchronized block as you can see in the code but still no luck.