Home> Java> javaTutorial> body text

Singleton and Unmodifiable Collections and Maps

WBOY
Release: 2024-07-17 20:41:41
Original
538 people have browsed it

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.

Image description

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!