Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Case : Collection.singletonList Vs Collection.unmodifiableList

Tags:

java

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.

like image 421
Oomph Fortuity Avatar asked Nov 21 '17 11:11

Oomph Fortuity


People also ask

What is collections singletonList?

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.

Are singletonList collections immutable?

The singletonList() method of Java Collections class is used to get an immutable list which contains only the specified object.

What is the use of singletonList?

The singletonList(T) method is used to return an immutable list containing only the specified object.

What are collections in Java 8?

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).


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.

like image 156
Leo Aso Avatar answered Oct 18 '22 20:10

Leo Aso