Skip to content

Instantly share code, notes, and snippets.

@ffbit
Last active December 12, 2015 09:19
Show Gist options
  • Select an option

  • Save ffbit/4751095 to your computer and use it in GitHub Desktop.

Select an option

Save ffbit/4751095 to your computer and use it in GitHub Desktop.
Unmodifiable list, set and collection if Java
package com.ffbit.collections;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
public class CollectionsTest {
private List<Integer> list;
private Set<Integer> set;
private Collection<Integer> collection;
@Before
public void setUp() {
list = new ArrayList<Integer>();
set = new HashSet<Integer>();
collection = new LinkedList<Integer>();
}
@Test
public void unmodifiableListShouldBeEqualToModifiedOriginOne() {
List<Integer> unmodifiable = Collections.unmodifiableList(list);
list.add(1);
assertThat(unmodifiable, is(list));
}
@Test
public void unmodifiableSetShouldBeEqualToModifiedOriginOne() {
Set<Integer> unmodifiable = Collections.unmodifiableSet(set);
set.add(1);
assertThat(unmodifiable, is(set));
}
@Test
public void unmodifiableCollectionShouldBeEqualToModifiedOriginOne() {
Collection<Integer> unmodifiable = Collections
.unmodifiableCollection(collection);
collection.add(1);
// java.util.Collections.UnmodifiableCollection does not override the
// java.lang.Object.equals(Object o) method.
assertThat(unmodifiable, is(not(collection)));
assertThat(unmodifiable, hasItems(collection.toArray(new Integer[] {})));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment