How to create an Un-Modifiable Collection aka Read-Only Collections

Java Collections Class supports various utility methods to create a unmodifiable data-structure

Important Points

  • This does not act on the original data-structure. Instead it takes the original data-structure and returns a copy which is un-modifiable
  • It also does not make the inner data-structure read-only. For example if a List contains another List then only the outermost list is read-only . We can still get the reference of inner list and modify it
<T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
<T> Set<T> unmodifiableSet(Set<? extends T> s)
<T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
<T> List<T> unmodifiableList(List<? extends T> list)
<K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
<K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Cheat Sheet To JAVA Latest Technology

%d bloggers like this: