Unmodifiable Collections

The Collections API provides a set of static methods that create unmodifiable wrappers for collections. Unmodifiable wrappers throw UnsupportedOperationExceptions if attempts are made to modify the collection. Headers for these methods are listed in Fig. 19.23. Details about these methods are available at java.sun.com/j2se/5.0/docs/api/java/util/Collections.html. All these methods take a generic type and return an unmodifiable view of the generic type. For example, the following code creates an unmodifiable List (list2) that stores String objects:

List< String > list1 = new ArrayList< String >(); List< String > list2 = Collections.unmodifiableList( list1 );

Figure 19.23. Unmodifiable wrapper methods.

(This item is displayed on page 951 in the print version)

public static method headers

< T > Collection< T > unmodifiableCollection( Collection< T > c )

< T > List< T > unmodifiableList( List< T > aList )

< T > Set< T > unmodifiableSet( Set< T > s )

< T > SortedSet< T > unmodifiableSortedSet( SortedSet< T > s )

< K, V > Map< K, V > unmodifiableMap( Map< K, V > m )

< K, V > SortedMap< K, V > unmodifiableSortedMap( SortedMap< K, V > m )

Software Engineering Observation 19.5

You can use an unmodifiable wrapper to create a collection that offers read-only access to others, while allowing readwrite access to yourself. You do this simply by giving others a reference to the unmodifiable wrapper while retaining for yourself a reference to the original collection.

Категории