-1

Below is some code (removed much of it for clarity) which shows my issue of concurrent list modification:

for (final Week week : this.demand.getWeeks().getAllWeeks()) {
    final List<Week> weeksExcludingThisWeek = this.demand.getWeeks().getAllWeeks();
    weeksExcludingThisWeek.remove(week);
}

As far as I was aware I was removing the reference to the same week object, but in a different list than is used in the for loop.

How do I prevent this from occurring?

Dr Ken Reid
  • 515
  • 4
  • 19

3 Answers3

2

Actually copy it into a new list before removing the element:

List<Week> weeksExcludingThisWeek = new ArrayList<>(this.demand.getWeeks().getAllWeeks());

You are currently removing the week from the same list you are iterating.

Andy Turner
  • 131,952
  • 11
  • 151
  • 228
2

Use iterator to avoid ConcurrentModificationExceptions

Have a look at docs: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

You will find:

Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics

Andy Turner
  • 131,952
  • 11
  • 151
  • 228
Patrik Mihalčin
  • 2,651
  • 5
  • 31
  • 59
1

Here you are using this.demand.getWeeks().getAllWeeks() For both iteration variable week and inside for loop variable weeksExcludingThisWeek .

Same reference in two object that is the issue. You couldn't modify current iterating object inside the loop.

Create new object inside loop, new ArrayList(this.demand.getWeeks().getAllWeeks())

saravanakumar
  • 1,727
  • 4
  • 20
  • 35