Arrays.asList() vs Collections.singletonList()
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.
I would just add that the singletonlist is not backed by an array and just has a reference to that one item. Presumably, it would take less memory and can be significant depending on the number of lists you want to create.