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

Collections.unmodifiableCollection for Generic Types

Use Collections.unmodifiableCollection for any Collection subtype and understand when this generic method is appropriate.

Collections.unmodifiableCollection for Generic Types

You'll learn how to create an unmodifiable view of any Collection type using a generic method.

So far, you've seen specific unmodifiable wrappers like unmodifiableList(), unmodifiableSet(), and unmodifiableMap(). But what if you're working with a method or variable declared as the general Collection<E> type, rather than a specific subtype?

The Collections.unmodifiableCollection() method provides a generic solution that works with any Collection subtype—whether it's a List, Set, Queue, or any other implementation. This method returns an unmodifiable view of the given collection, preventing modifications while preserving the original collection's type information through generics.

When to Use It

Use Collections.unmodifiableCollection() when:

  • You're working with generic Collection<E> references
  • You want to write code that works with any collection type
  • The specific collection type doesn't matter for your use case

For example, if a method accepts Collection<String> as a parameter and you want to protect it from modifications, unmodifiableCollection() is the appropriate choice.

Why It Matters

This generic approach gives you flexibility. Instead of checking "Is this a List? Use unmodifiableList(). Is this a Set? Use unmodifiableSet()," you can handle all cases uniformly. The returned view still enforces read-only access—any attempt to modify throws UnsupportedOperationException.

Remember: like other unmodifiable views, this creates a view, not a copy. Changes to the underlying collection will still be visible through the unmodifiable wrapper.

Key Takeaway: Use Collections.unmodifiableCollection() as a type-agnostic way to create read-only views of any Collection implementation when working with generic Collection references.