Skip to content

Commit 4ba5e3f

Browse files
committed
Merge branch 'foo' of https://github.com/mogronalol/tutorials into mogronalol-foo
2 parents c13453d + 0a444d3 commit 4ba5e3f

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)