Home >Java >javaTutorial >Singleton and Unmodifiable Collections and Maps
You can create singleton sets, lists, and maps and unmodifiable sets, lists, and maps using the static methods in the Collections class. The Collections class contains the static methods for lists and collections. It also contains the methods for creating immutable singleton sets, lists, and maps, and for creating read-only sets, lists, and maps, as shown in Figure below.
The Collections class defines three constants—EMPTY_SET, EMPTY_LIST, and EMPTY_MAP—for an empty set, an empty list, and an empty map. These collections are immutable. The class also provides the singleton(Object o) method for creating an immutable set containing only a single item, the singletonList(Object o) method for creating an immutable list containing only a single item, and the singletonMap(Object key, Object value) method for creating an immutable map containing only a single entry.
The Collections class also provides six static methods for returning read-only views for collections: unmodifiableCollection(Collection c), unmodifiableList(List list), unmodifiableMap(Map m), unmodifiableSet(Set set), unmodifiableSortedMap(SortedMap m), and unmodifiableSortedSet(Sorted Set s). This type of view is like a reference to the actual collection. But you cannot modify the collection through a read-only view. Attempting to modify a collection through a read-only view will cause an UnsupportedOperationException.
The above is the detailed content of Singleton and Unmodifiable Collections and Maps. For more information, please follow other related articles on the PHP Chinese website!