0

I have multiple sets of objects. I want to add the id (stored in array lists of the objects) to previously existing objects if names(strings) of two objects are the same.

    for (OperatorClass s1: set_2)
        {
            for (OperatorClass s2: set_4)
            {
                if (s2.get_Name().equals(s1.get_Name()))
                {
                    set_4.remove(s2);
                    s2.add_id(s1.get_Id().get(0));
                    set_4.add(s2);
                }
            }
        }

I know this will give a concurrency exception at run time. Can someone guide me on how to deal with this issue?

Aman
  • 735
  • 1
  • 6
  • 19
  • 1
    Use `iterators` instead for safer operations –  Aug 16 '17 at 07:57
  • 1
    why are you removing and adding s2? Java uses reference so you cna update the actual reference as it is. – Amber Beriwal Aug 16 '17 at 07:57
  • 1
    You CANNOT add/remove item to a set while iterating it, This is a big NO-NO – Gal Dreiman Aug 16 '17 at 07:58
  • 1
    @GalDreiman of course you can - with a proper iterator. – Eugene Aug 16 '17 at 07:58
  • 1
    It is not a 'concurrency exception' it is a 'ConcurrentModificationException', which means you (or another thread) is modifying the collection, while you are iterating over it. Which is exactly what you are doing. **Don't iterate over a collection and modify it in that loop**. – Mark Rotteveel Aug 16 '17 at 07:59
  • @Eugene, you're right, it is possible, but not as presented in this example – Gal Dreiman Aug 16 '17 at 08:01
  • Create a new set from set_2 and then just add to that. That way you do not have to modify the one you are iterating over. – Ouney Aug 16 '17 at 08:01

0 Answers0