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[]{"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);

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.