Create an immutable collection in Java

Description

The following code shows how to create an immutable collection.

Example


//ww  w.  java 2  s  .  c  o m
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

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 code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet