|
| 1 | +package com.baeldung.java.concurrentmodification; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.ConcurrentModificationException; |
| 7 | +import java.util.Iterator; |
| 8 | + |
| 9 | +import static org.assertj.core.api.Assertions.assertThat; |
| 10 | +import static org.assertj.core.util.Lists.newArrayList; |
| 11 | + |
| 12 | +public class ConcurrentModificationUnitTest { |
| 13 | + @Test(expected = ConcurrentModificationException.class) |
| 14 | + public void givenIterating_whenRemoving_thenThrowException() throws InterruptedException { |
| 15 | + |
| 16 | + ArrayList<Integer> integers = newArrayList(1, 2, 3); |
| 17 | + |
| 18 | + for (Integer integer : integers) { |
| 19 | + integers.remove(1); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException { |
| 25 | + |
| 26 | + ArrayList<Integer> integers = newArrayList(1, 2, 3); |
| 27 | + |
| 28 | + for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) { |
| 29 | + Integer integer = iterator.next(); |
| 30 | + if(integer == 2) { |
| 31 | + iterator.remove(); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + assertThat(integers).containsExactly(1, 3); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void givenIterating_whenUsingRemovalList_thenNoError() throws InterruptedException { |
| 40 | + |
| 41 | + ArrayList<Integer> integers = newArrayList(1, 2, 3); |
| 42 | + ArrayList<Integer> toRemove = newArrayList(); |
| 43 | + |
| 44 | + for (Integer integer : integers) { |
| 45 | + if(integer == 2) { |
| 46 | + toRemove.add(integer); |
| 47 | + } |
| 48 | + } |
| 49 | + integers.removeAll(toRemove); |
| 50 | + |
| 51 | + assertThat(integers).containsExactly(1, 3); |
| 52 | + } |
| 53 | + |
| 54 | + @Test |
| 55 | + public void whenUsingRemoveIf_thenRemoveElements() throws InterruptedException { |
| 56 | + |
| 57 | + ArrayList<Integer> integers = newArrayList(1, 2, 3); |
| 58 | + |
| 59 | + integers.removeIf(i -> i == 2); |
| 60 | + |
| 61 | + assertThat(integers).containsExactly(1, 3); |
| 62 | + } |
| 63 | +} |
0 commit comments