Making Collections Unmodifiable

Let's discuss how a collection can be made unmodifiable.

We'll cover the following

Let’s say we have created a collection where we have added some important data. We want others to read this data, but they should not be allowed to modify the data in this Collection. The Collections class provides certain methods that can be used to make our Collection unmodifiable. These methods return a collection in which if someone tries to add or remove an element, then UnsupportedOperationException is thrown.

This feature is particularly useful if our Collection contains some sensitive data. We need to only give read access to our data, but we don’t want others to accidentally modify it.

Following is the list of methods available to make Collections unmodifiable:

  1. unmodifiableList(List<? extends T> list)
  2. unmodifiableSet(Set<? extends T> s)
  3. unmodifiableMap(Map<? extends K, ? extends V> m)
  4. unmodifiableCollection(Collection<? extends T> c)
  5. unmodifiableSortedMap(SortedMap<K,? extends V> m)
  6. unmodifiableSortedSet(SortedSet<T> s)

We will not look at examples of each of these methods, as they are essentially the same. We will only look at unmodifiableList().

Get hands-on with 1200+ tech skills courses.