0

I have looked at other questions that deal with similar problems, but it seems that this particular case is rather unique.

The code below is supposed to go through a list of Events and put them in a map if their times overlap.

// identify events that occur at the same time
List<Event> remainingEvents = new LinkedList<>();
remainingEvents = Event.getAllEvents();

for (Event event1 : Event.getAllEvents()) {
    for (Event event2 : remainingEvents) {

        // check if it is the same event
        if (event1 == event2)
            continue;

        // check whether they overlap
        if (event1.overlapsWith(event2)) {
            simultEvents.put(event1, event2);
        }
    }

    // event1 is now exhausted
    remainingEvents.remove(event1);
}

Notice that I am modifying the remainingEvents list after the iteration is complete, not during. Therefore, I do not understand why I am getting a ConccurentModificationException.

Elipse also tells me that the error occurs on this line:

 for (Event event1 : Event.getAllEvents()) {

which makes no sense since I am not modifying anything relating to it.

Note that this is not a duplicate because I am not modifying the list until I am done Iterating with it (unlike other questions), and the error occurs on a line that has nothing to do with the removal

jeanluc
  • 1,608
  • 1
  • 14
  • 28
  • Check your loop nesting. You're removing elements unsafely in the outermost loop. – Makoto Apr 24 '15 at 03:40
  • But when that removal occurs, the respective list is no longer being iterated upon. Also, Makoto, you should not be so careless when marking questions as duplicates. – jeanluc Apr 24 '15 at 03:41
  • 3
    `remainingEvents = Event.getAllEvents();` - both loops iterate over the same list. – Eran Apr 24 '15 at 03:46
  • You maybe need `remainingEvents = new LinkedList<>(Event.getAllEvents());` This creates a copy. – Radiodef Apr 24 '15 at 03:50
  • Yes that was the problem and the solution. Thank everyone but Makoto for contributing. – jeanluc Apr 24 '15 at 03:51

0 Answers0