|
| 1 | +package com.baeldung.java9.list.immutable; |
| 2 | + |
| 3 | +import com.google.common.collect.ImmutableList; |
| 4 | +import org.apache.commons.collections4.ListUtils; |
| 5 | +import org.junit.Test; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.Arrays; |
| 9 | +import java.util.Collections; |
| 10 | +import java.util.List; |
| 11 | + |
| 12 | +public class ImmutableArrayListUnitTest { |
| 13 | + |
| 14 | + @Test(expected = UnsupportedOperationException.class) |
| 15 | + public final void givenUsingTheJdk_whenUnmodifiableListIsCreated_thenNotModifiable() { |
| 16 | + final List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three")); |
| 17 | + final List<String> unmodifiableList = Collections.unmodifiableList(list); |
| 18 | + unmodifiableList.add("four"); |
| 19 | + } |
| 20 | + |
| 21 | + @Test(expected = UnsupportedOperationException.class) |
| 22 | + public final void givenUsingTheJava9_whenUnmodifiableListIsCreated_thenNotModifiable() { |
| 23 | + final List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three")); |
| 24 | + final List<String> unmodifiableList = List.of(list.toArray(new String[]{})); |
| 25 | + unmodifiableList.add("four"); |
| 26 | + } |
| 27 | + |
| 28 | + @Test(expected = UnsupportedOperationException.class) |
| 29 | + public final void givenUsingGuava_whenUnmodifiableListIsCreated_thenNotModifiable() { |
| 30 | + final List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three")); |
| 31 | + final List<String> unmodifiableList = ImmutableList.copyOf(list); |
| 32 | + unmodifiableList.add("four"); |
| 33 | + } |
| 34 | + |
| 35 | + @Test(expected = UnsupportedOperationException.class) |
| 36 | + public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreated_thenNoLongerModifiable() { |
| 37 | + final List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three")); |
| 38 | + final ImmutableList<String> unmodifiableList = ImmutableList.<String>builder().addAll(list).build(); |
| 39 | + unmodifiableList.add("four"); |
| 40 | + } |
| 41 | + |
| 42 | + @Test(expected = UnsupportedOperationException.class) |
| 43 | + public final void givenUsingCommonsCollections_whenUnmodifiableListIsCreated_thenNotModifiable() { |
| 44 | + final List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three")); |
| 45 | + final List<String> unmodifiableList = ListUtils.unmodifiableList(list); |
| 46 | + unmodifiableList.add("four"); |
| 47 | + } |
| 48 | +} |
0 commit comments