Java Collections unmodifiableSet() Method
Example
Try to add an item to a read-only set:
import java.util.HashSet;
import java.util.Collections;
import java.util.Set;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
Set<String> readOnly = Collections.unmodifiableSet(cars);
try {
readOnly.add("BMW");
} catch (UnsupportedOperationException e) {
System.out.println("Error: the set cannot be changed.");
}
}
}
Definition and Usage
The unmodifiableSet() method returns an unmodifiable (read-only) view of a set. You can read the items, but you cannot add or remove them. If you try, Java throws an UnsupportedOperationException.
The view is not a copy. If the original set changes, the view shows the change.
Syntax
public static Set<T> unmodifiableSet(Set<T> set)
T refers to the data type of items in the set.
Parameter Values
| Parameter | Description |
|---|---|
| set | Required. The set to make a read-only view of. |
Technical Details
| Returns: | A read-only Set that shows the items of the original set. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods