e martë, 12 qershor 2007

Read-Only Collection or unmodifiable

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);

Nuk ka komente: