The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Collections  [7 examples]

e348. Making a Collection Read-Only

Making a collection read-only involves wrapping the collection in another object whose mutation methods all throw UnsupportedOperationException.
    List stuff = Arrays.asList(new String[]{"a", "b"});
    
    // Make a list read-only
    List list = new ArrayList(stuff);
    list = Collections.unmodifiableList(list);
    
    try {
        // Try modifying the list
        list.set(0, "new value");
    } catch (UnsupportedOperationException e) {
        // Can't modify
    }
    
    // Make a set read-only
    Set set = new HashSet(stuff);
    set = Collections.unmodifiableSet(set);
    
    // Make a map read-only
    Map map = new HashMap();
    // Add key/value pairs ...
    map = Collections.unmodifiableMap(map);

 Related Examples
e342. Implementing a Queue
e343. Implementing a Stack
e344. Implementing a Least-Recently-Used (LRU) Cache
e345. Listing the Elements of a Collection
e346. Storing Primitive Types in a Collection
e347. Creating a Copy of a Collection

See also: Arrays    Bits    Dates    Hash Tables    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.