|
1 | 1 | package ai.timefold.solver.core.impl.bavet.common.index; |
2 | 2 |
|
3 | | -import ai.timefold.solver.core.impl.util.ElementAwareList; |
4 | | -import org.jspecify.annotations.NullMarked; |
5 | | -import org.jspecify.annotations.Nullable; |
6 | | - |
7 | 3 | import java.util.ArrayList; |
8 | 4 | import java.util.Collections; |
9 | 5 | import java.util.List; |
10 | 6 | import java.util.Objects; |
11 | 7 | import java.util.function.Consumer; |
12 | 8 | import java.util.function.Predicate; |
13 | 9 |
|
| 10 | +import ai.timefold.solver.core.impl.util.ElementAwareList; |
| 11 | + |
| 12 | +import org.jspecify.annotations.NullMarked; |
| 13 | +import org.jspecify.annotations.Nullable; |
| 14 | + |
14 | 15 | /** |
15 | 16 | * {@link ArrayList}-backed set which allows to {@link #remove(Object)} an element |
16 | 17 | * without knowing its position and without an expensive lookup. |
@@ -161,10 +162,14 @@ private void forEachNonCompacting(Consumer<T> elementConsumer) { |
161 | 162 | } |
162 | 163 |
|
163 | 164 | private void forEachNonCompacting(Consumer<T> elementConsumer, int startingIndex) { |
164 | | - for (var i = startingIndex; i <= lastElementPosition; i++) { |
| 165 | + var oldLastElementPosition = lastElementPosition; |
| 166 | + for (var i = startingIndex; i <= oldLastElementPosition; i++) { |
165 | 167 | var element = elementList.get(i); |
166 | 168 | if (element != null) { |
167 | 169 | elementConsumer.accept(element); |
| 170 | + if (lastElementPosition != oldLastElementPosition) { |
| 171 | + throw new IllegalStateException("Impossible state: the IndexedSet was modified while being iterated."); |
| 172 | + } |
168 | 173 | } |
169 | 174 | } |
170 | 175 | } |
@@ -239,11 +244,15 @@ private void forEachCompacting(Consumer<T> elementConsumer) { |
239 | 244 | } |
240 | 245 |
|
241 | 246 | private @Nullable T findFirstNonCompacting(Predicate<T> elementPredicate, int startingIndex) { |
242 | | - for (var i = startingIndex; i <= lastElementPosition; i++) { |
| 247 | + var oldLastElementPosition = lastElementPosition; |
| 248 | + for (var i = startingIndex; i <= oldLastElementPosition; i++) { |
243 | 249 | var element = elementList.get(i); |
244 | 250 | if (element != null && elementPredicate.test(element)) { |
245 | 251 | return element; |
246 | 252 | } |
| 253 | + if (lastElementPosition != oldLastElementPosition) { |
| 254 | + throw new IllegalStateException("Impossible state: the IndexedSet was modified while being searched."); |
| 255 | + } |
247 | 256 | } |
248 | 257 | return null; |
249 | 258 | } |
|
0 commit comments