LinkedHashMap: How to remove element?

Hi,

I have a LinkedHashMap that needs to be updated on a regular basis. I can update the values andput them back into the LHM without any problems, but can'tremove any entries without causing a concurrent modification exception.

I want to remove key-value pairs when the value falls below 0. How can I do that?

Code snippet:

Point p;

Integer[] data =new Integer[1];

int pheremoneStrength = 0;

for(Map.Entry<Point,Integer[]> e : pheremoneMap.entrySet())

{

p = e.getKey();

data = e.getValue();

pheremoneStrength = data[0];

pheremoneStrength -= 1;

data[0] = pheremoneStrength;

pheremoneMap.put(p,data);

if(pheremoneStrength <= 0)//causes concurrent mod ex.

{

pheremoneMap.remove(p);

}

}

Thanks

[1110 byte] By [hasman001a] at [2007-11-27 11:17:29]
# 1

How embarrassing, just synchronize the map and then...

pheremoneMap.entrySet().remove(p);

hasman001a at 2007-7-29 14:25:11 > top of Java-index,Core,Core APIs...
# 2

> pheremoneMap.entrySet().remove(p);

That doesn't cause ConcurrentModificationException?

I would have thought you needed to do something like:Point p;

Integer[] data = new Integer[1];

int pheremoneStrength = 0;

Iterator<Map.Entry<Point, Integer[]>> it = pheremoneMap.entrySet().iterator();

while (it.hasNext()) {

Map.Entry<Point,Integer[]> e = it.next();

p = e.getKey();

data = e.getValue();

pheremoneStrength = data[0];

pheremoneStrength -= 1;

data[0] = pheremoneStrength;

// Could just do

//data[0]--;

// instead of previous 3 lines

// No need since you are modifying a reference already in the map at that key

//pheremoneMap.put(p,data);

if(pheremoneStrength <= 0) {

it.remove();

}

}

dwga at 2007-7-29 14:25:11 > top of Java-index,Core,Core APIs...
# 3

The correct way to remove during iteration--whether multithreading or not--is to use an explicit Iterator, rather than enhanced for loop, and call Iterator's remove method.

If you're multithreading, then you'll also need to sync around the entire iteration, and also make sure all other accesses to the map are synced.

jverda at 2007-7-29 14:25:11 > top of Java-index,Core,Core APIs...
# 4

Thank you very much, dwg and jverd.

I just came back to say that though my attempt compiled and ran, nothing happened!

dwg, your code works perfectly; jverd, thanks for the explanation of the finer points.

H.

hasman001a at 2007-7-29 14:25:11 > top of Java-index,Core,Core APIs...
# 5

Well, what did you expect to happen?

jverda at 2007-7-29 14:25:11 > top of Java-index,Core,Core APIs...