You can create singleton sets, lists, and maps and unmodifiable sets, lists, and maps using the static methods in theCollectionsclass. TheCollectionsclass 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.
TheCollectionsclass defines three constants—EMPTY_SET,EMPTY_LIST, andEMPTY_MAP—for an empty set, an empty list, and an empty map. These collections are immutable. The class also provides thesingleton(Object o)method for creating an immutable set containing only a single item, thesingletonList(Object o)method for creating an immutable list containing only a single item, and thesingletonMap(Object key, Object value)method for creating an immutable map containing only a single entry.
TheCollectionsclass also provides six static methods for returningread-only views for collections:unmodifiableCollection(Collection c),unmodifiableList(List list),unmodifiableMap(Map m),unmodifiableSet(Set set),unmodifiableSortedMap(SortedMap m), andunmodifiableSortedSet(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 anUnsupportedOperationException.
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!