2

So i was working on a simple Java code

i have this:

HashMap<ObjectKey,ArrayList<DifferentObject>> HP;

So i used it how i wanted and it worked heres the first code:

FillHashMap(HP);
for(ObjectKey k:HP.keySet()){
    ArrayList<DifferentObject> temp=HP.get(k);
    for(Iterator<DifferentObject> it=temp.iterator(); it.hasNext();){
        if(it.hasNext()){
            DifferentObject OB=iterator.next();
            if(OB.Data<OtherData && OB.Time<CurrentTime){
                it.remove();
            }
        }
    }
}

And it works like a charm, so i went out to clean my code a bit make it more presentable and now it looks like this:

FillHashMap(HP);
for(Object k:HP.keySet()){
  for(Iterator<DifferentObject> it=HP.get(k).iterator();it.hasNext();){
      DifferentObject OB=it.next(); (*)
      if(Condition(OB)){
           it.remove();
      }
}      
}

And then i get the ConcurrentModificationException on the line with the (*) The other method that changes HP is FillHashMap and its already over by the time it reaches the for-each cycle, it really is the same code right?

Then why is giving me the error now?

Any remote help or suggestion would be apreciated. Thank you.

EDIT: So i went back to FillHashMap method:

FillHashMap(HashMap HP){
   Differentobject x=new DifferentObject(); 
   for(iterator over hashmap){
       ArrayList<Different Object> temp= HP.get(k);
       temp.SetSomething(int a);
       temp.add(x)
   }

}

if i comment the temp.add the error is gone, offcourse the program is not doing what is suppoused to do anymore, but at least now i now where it is.

By the time the loop of the 2 bit of code executes, FillHashMap should be over, but i guess its not.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Luchingador
  • 31
  • 1
  • 4

0 Answers0