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[]{"m", "d"});
// Make a list read-only
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);
try {
// Try modifying the list
list.set(0, "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);