Use Case : Collection.singletonList Vs Collection.unmodifiableList

Viewed 2197

As I aware that both Collection methods provides read-only access to returned list and throws Exception on modification.

I need to understand Use Cases of both so that when to use singletonList and unmodifiableList.

This might help me to grow understanding of both based on their usage.

1 Answers

singletonList takes an item, and creates an immutable list containing only that item. unmodifiableList takes a list, and creates an immutable list that references that list. It is analogous to the difference between add and addAll. One takes an item, one takes a list containing items.

So if you have a List<...> list, singletonList (list).get(0) returns list but unmodifiableList (list).get(0) returns list.get(0). And the former is rarely useful.

Related