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.
The singletonList() method of java. util. Collections class is used to return an immutable list containing only the specified object. The returned list is serializable. This list will always contain only one element thus the name singleton list.
The singletonList() method of Java Collections class is used to get an immutable list which contains only the specified object.
The singletonList(T) method is used to return an immutable list containing only the specified object.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With