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:
unmodifiableList(List<? extends T> list)
unmodifiableSet(Set<? extends T> s)
unmodifiableMap(Map<? extends K, ? extends V> m)
unmodifiableCollection(Collection<? extends T> c)
unmodifiableSortedMap(SortedMap<K,? extends V> m)
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 1400+ tech skills courses.