-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
  • 577
  • 4
  • 22

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
  • 137,514
  • 11
  • 162
  • 243
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
  • 137,514
  • 11
  • 162
  • 243
Patrik Mihalčin
  • 3,341
  • 7
  • 33
  • 68
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,747
  • 4
  • 20
  • 38