DEV Community

Cover image for Singleton and Unmodifiable Collections and Maps
Paul Ngugi
Paul Ngugi

Posted on

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.

Image description

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay