After you've added all the necessary elements to a collection,
it may be convenient to treat that collection as read-only, to
prevent the accidental modification of the collection. To provide
this capability, the Collections
class provides six
factory methods, one for each of Collection
, List
,
Map
, Set
, SortedMap
, and SortedSet
.
Collection unmodifiableCollection(Collection
collection)
List unmodifiableList(List list)
Map unmodifiableMap(Map map)
Set unmodifiableSet(Set set)
SortedMap unmodifiableSortedMap(SortedMap map)
SortedSet unmodifiableSortedSet(SortedSet set)
Once you've filled the collection, replace the original reference with
the read-only reference. If you don't replace the original
reference, then the collection is not read-only, as you can still
use the original reference to modify the collection. The
following program demonstrates the proper way to make a
collection read-only. In addition, it shows what happens when you
try to modify a read-only collection.
import java.util.*;
public class ReadOnlyExample {
public static void main(String args[]) {
Set set = new HashSet();
set.add("Bernadine");
set.add("Elizabeth");
set.add("Gene");
set.add("Elizabeth");
set = Collections.unmodifiableSet(set);
set.add("Clara");
}
}
When the program is run and the last add()
operation is attempted on
the read-only set, an UnsupportedOperationException
is
thrown.