Skip to content

Commit 92e636d

Browse files
Checked collection methods (#17218)
* Initial commit for checked collection methods * Removed public * Fixed test as per review * Fixed test as per review * Clean imports * Fixed test name
1 parent 5f41a60 commit 92e636d

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.checkedcollections;
2+
3+
import java.util.Collection;
4+
5+
class DataProcessor {
6+
7+
public boolean checkPrefix(Collection<?> data) {
8+
boolean result = true;
9+
if (data != null) {
10+
for (Object item : data) {
11+
if (item != null && !((String) item).startsWith("DATA_")) {
12+
result = false;
13+
break;
14+
}
15+
}
16+
}
17+
return result;
18+
}
19+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.checkedcollections;
2+
3+
import static org.junit.jupiter.api.Assertions.assertThrows;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import java.util.ArrayList;
7+
import java.util.Collection;
8+
import java.util.Collections;
9+
10+
import org.junit.jupiter.api.Test;
11+
12+
class DataProcessorUnitTest {
13+
14+
@Test
15+
void givenGenericCollection_whenInvalidTypeDataAdded_thenFailsAfterInvocation() {
16+
Collection data = new ArrayList<>();
17+
data.add("DATA_ONE");
18+
data.add("DATA_TWO");
19+
data.add(3); // should have failed here
20+
21+
DataProcessor dataProcessor = new DataProcessor();
22+
23+
assertThrows(ClassCastException.class, () -> dataProcessor.checkPrefix(data)); // but fails here
24+
}
25+
26+
@Test
27+
void givenGenericCollection_whenInvalidTypeDataAdded_thenFailsAfterAdding() {
28+
Collection data = Collections.checkedCollection(new ArrayList<>(), String.class);
29+
data.add("DATA_ONE");
30+
data.add("DATA_TWO");
31+
32+
assertThrows(ClassCastException.class, () -> {
33+
data.add(3); // fails here
34+
});
35+
36+
DataProcessor dataProcessor = new DataProcessor();
37+
final boolean result = dataProcessor.checkPrefix(data);
38+
assertTrue(result);
39+
40+
}
41+
}

0 commit comments

Comments
 (0)