Collection unmodifiable

In this chapter you will learn:

  1. Return an unmodifiable view of collections
  2. What if you try to change an unmodifiable collection

Return an unmodifiable view of collections

Sometimes we need to make a collection not changeable. For example, when returning a collection from a method we can return a unchangeable list or unchangeable map.

The following methods from Collections class make collection unchangeable.

  • static<T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
  • static<T> List<T> unmodifiableList(List<? extends T> list)
  • static<K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
  • static<T> Set<T> unmodifiableSet(Set<? extends T> s)
  • static<K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)
  • static<T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
//from   j  a  va 2  s. c  om
public class Main {

  public static void main(String args[]) {
    List<Character> list = new ArrayList<Character>();

    list.add('X');

    System.out.println("Element added to list: " + list.get(0));

    Collection<Character> immutableCol = Collections.unmodifiableCollection(list);

    immutableCol.add('Y');
  }
}

The output:

Try to change an unmodifiable collection

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*from j  a v a 2s. c  om*/
public class Main {
  public static void main(String args[]) throws Exception {

    List<String> list = new ArrayList<String>();
    list.add("A");
    list.add("B");
    list.add("C");
    list = Collections.unmodifiableList(list);
    list.add(1, "G");

    System.out.println(list);

  }
}

The output:

From the output we can see that a java.lang.UnsupportedOperationException is returned if we try to change an unmodifiable list.

Next chapter...

What you will learn in the next chapter:

  1. Get a synchronized collection
  2. How to create a synchronized Map
Home » Java Tutorial » Collections
Iterator
ListIterator
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue