Course contentsShow
← Java
Lesson 1240 of 2,87028. Collections Utility ClassFree lesson

Collections.unmodifiableSet and unmodifiableMap

Wrap Set and Map instances with unmodifiable views to prevent external modification while preserving read access.

Collections.unmodifiableSet and unmodifiableMap

What You'll Learn

You'll learn how to create read-only wrappers around Set and Map collections to prevent accidental modification while still allowing full read access.

The Core Idea

Just like Collections.unmodifiableList creates a protective wrapper around lists, Java provides unmodifiableSet and unmodifiableMap to do the same for Set and Map collections. Think of these as putting your collection behind glass in a museum—everyone can look, but nobody can touch.

When you wrap a Set or Map with these methods, you get a view of the original collection. You can read all the data, but any attempt to add, remove, or modify elements throws an UnsupportedOperationException.

Why This Matters

These wrappers are perfect when you need to:

  • Share collection data with other code without risking modification
  • Expose internal data structures from a class safely
  • Enforce immutability at the API boundary

The Important Details

For Sets:

Set<String> originalSet = new HashSet<>();
originalSet.add("apple");
originalSet.add("banana");

Set<String> readOnly = Collections.unmodifiableSet(originalSet);
// readOnly.add("cherry"); // Would throw UnsupportedOperationException

For Maps:

Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("score", 100);

Map<String, Integer> readOnly = Collections.unmodifiableMap(originalMap);
// readOnly.put("bonus", 50); // Would throw UnsupportedOperationException

Remember: these are views, not copies. If the original collection changes, the unmodifiable wrapper reflects those changes.

Key Takeaway: Use Collections.unmodifiableSet and unmodifiableMap to create read-only views that prevent modification while preserving full read access—perfect for safely sharing data without allowing external changes.