Collection unmodifiable
In this chapter you will learn:
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: