Create a read-only Set in Java
Description
The following code shows how to create a read-only Set.
Example
/*from w ww . j a v a2 s. co m*/
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] argv) throws Exception {
List stuff = Arrays.asList(new String[] { "a", "b" });
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
try {
set.add("new value");
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
}
}
The code above generates the following result.