Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.asList() vs Collections.singletonList()

Is there an advantage (or much of a difference) to using Arrays.asList(something) over Collections.singletonList(something) to make a list containing one item? The latter makes the returned list immutable as well.

like image 821
Howard Grimberg Avatar asked Sep 25 '22 04:09

Howard Grimberg


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.

How is array asList () different?

asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.

What does arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.

What is arrays asList () in Java?

The java.util.Arrays.asList(T... a) returns a fixed-size list backed by the specified array. ( Changes to the returned list "write through" to the array.)


1 Answers

Collections.singletonList(something) is immutable whereas Arrays.asList(something) is a fixed size List representation of an Array where the List and Array gets joined in the heap.

Arrays.asList(something) allows non-structural changes made to it, which gets reflected to both the List and the conjoined array. It throws UnsupportedOperationException for adding, removing elements although you can set an element for a particular index.

Any changes made to the List returned by Collections.singletonList(something) will result in UnsupportedOperationException.

Also, the capacity of the List returned by Collections.singletonList(something) will always be 1 unlike Arrays.asList(something) whose capacity will be the size of the backed array.

like image 242
Kumar Abhinav Avatar answered Oct 23 '22 01:10

Kumar Abhinav