Java Reference
In-Depth Information
Read-Only Views of Collections
You can get a read-only view (also called unmodifiable view) of a collection. This is useful when you want to pass
around your collection to other methods and you do not want the called method to modify your collection. In such
cases, you need to pass a read-only view of your collection to those methods.
The Collections class offers the following methods to get read-only views of different types of collections:
<T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
<T> List<T> unmodifiableList(List<? extends T> list)
<K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
<K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K,? extends V> m)
<T> Set<T> unmodifiableSet(Set<? extends T> s)
<T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)
static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
<K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)
Using any of these methods is straightforward. You pass a collection of a specific type and you get a read-only
collection of the same type.
Synchronized View of a Collection
Most collections that are members of the Collections Framework discussed in this chapter are not thread-safe and
you should not use them in a multithreaded environment. Note that the collections whose names have the word
“concurrent” in them are designed to be thread-safe. You can get a synchronized view of a collection using one of the
following static methods of the Collections class. You have one method for each collection type to return the same
type of synchronized version of the collection. The methods are
<T> Collection<T> synchronizedCollection(Collection<T> c)
<T> List<T> synchronizedList(List<T> list)
<K,V> Map<K,V> synchronizedMap(Map<K,V> m)
<K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)
<T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s)
<T> Set<T> synchronizedSet(Set<T> s)
<T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
<K,V> SortedMap<K,V> synchronizedSortedMap (SortedMap<K,V> m)
You need to pay attention when working with a synchronized view of a collection. All reads and writes through
the synchronized view will be thread-safe, except when you are iterating over elements of the collection using an
iterator. You must synchronize the entire collection during the time you get the iterator and use it. The following
snippet of code illustrates this concept:
// Suppose you have a Set
Set s = ...; // unsynchronized set
 
Search WWH ::




Custom Search