221

What is the use of Collections.singletonList() in Java? I understand that it returns a list with one element. Why would I want to have a separate method to do that? How does immutability play a role here?

Are there any special useful use-cases for this method rather than just being a convenient method?

hackjutsu
  • 8,336
  • 13
  • 47
  • 87
Debajit
  • 46,327
  • 33
  • 91
  • 100
  • 7
    Here's example of how it can be useful - http://stackoverflow.com/a/1239631/360811 – shabunc May 15 '13 at 11:51
  • 3
    possible duplicate of [Arrays.asList() vs Collections.singletonList()](http://stackoverflow.com/questions/26027396/arrays-aslist-vs-collections-singletonlist) – sschuberth Sep 16 '15 at 12:04
  • 5
    @sschuberth, please compare the dates for the questions. OP was not aware s/he could be duplicating a future question – KumarAnkit Apr 03 '19 at 10:35
  • True, @KumarAnkit, but links to duplicates are still useful for people looking for alternative / potentially better answers. In fact I believe linking as duplicate should be regarded as a bidirectional thing, and the better questions / answers should be kept, no matter whether these are the older or newer. – sschuberth Apr 03 '19 at 14:11
  • 1
    @sschuberth, good point, but it should be categorised as similar, as this question here. – KumarAnkit Apr 04 '19 at 05:09
  • @sschuberth - It is not bi-directional. Closing a question as a duplicate prevents any more answers from being added to it. So, if someone incorrectly dup-close a question just because it is related, they are actually blocking off potentially useful new contributions. – Stephen C Apr 21 '20 at 08:49

6 Answers6

195

The javadoc says this:

"Returns an immutable list containing only the specified object. The returned list is serializable."

You ask:

Why would I want to have a separate method to do that?

Primarily as a convenience ... to save you having to write a sequence of statements to:

  • create an empty list object
  • add an element to it, and
  • wrap it with an immutable wrapper.

It may also be a bit faster and/or save a bit of memory, but it is unlikely that these small savings will be significant. (An application that creates vast numbers of singleton lists is unusual to say the least.)

How does immutability play a role here?

It is part of the specification of the method; see above.

Are there any special useful use-cases for this method, rather than just being a convenience method?

Clearly, there are use-cases where it is convenient to use the singletonList method. Indeed, any program where you need to use an immutable list with one element is a valid use-case. (It takes roughly zero imagination to think of one.)

But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Why is it named "singleton" ? Because it has a single item inside? It's quite confusing as "singleton" is supposed to be of single instance globally, yet you can create multiple instances of such a list (whether of same object within, or other objects)... – android developer Feb 15 '23 at 11:31
  • 1
    It comes from Mathematics: "Singleton ... 5: Mathematics. a set consisting of one given element." source: https://www.dictionary.com/browse/singleton . Also https://en.wikipedia.org/wiki/Singleton_(mathematics). – Stephen C Feb 15 '23 at 13:51
  • And note that the Wikipedia article cites Principia Mathematica (1910) as a source. So the mathematical definition has "first use" rights for the term relative to Go4 design patterns, etc. – Stephen C Feb 15 '23 at 13:59
  • I see. I thought "singleton" is in the same meaning of "Singleton design pattern", meaning only up to one instance of it. Seems confusing name now. All this time I thought this is the meaning. Now it has 2 different (yet a bit similar ) meanings... – android developer Feb 16 '23 at 14:05
  • *"There's a sign on the wall - But she wants to be sure - 'Cause you know, sometimes words have two meanings"* - Led Zeppelin – Stephen C Feb 16 '23 at 14:09
33

From the javadoc

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

example

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

Use it when code expects a read-only list, but you only want to pass one element in it. singletonList is (thread-)safe and fast.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
salsinga
  • 1,957
  • 1
  • 14
  • 26
  • 3
    Thanks, this is the better answer. You even give an example instead of simply saying "Clearly there are use cases, but I don't know about them". – theprogrammer Apr 03 '20 at 14:46
31

Here's one view on the singleton methods:

I have found these various "singleton" methods to be useful for passing a single value to an API that requires a collection of that value. Of course, this works best when the code processing the passed-in value does not need to add to the collection.

Jim Ferrans
  • 30,582
  • 12
  • 56
  • 83
  • Can you help me understand this part of the above comment? "Of course, this works best when the code processing the passed-in value does not need to add to the collection." I didn't get it. – Bilbo Baggins Sep 27 '16 at 06:07
  • 2
    I think he refers to not being able to modify the passed-in list, as it is an immutable one. – Daniel Higueras Oct 28 '16 at 07:21
  • 3
    @BilboBaggins - That statement was ironic. :-) The phrase "this works best when ..." is more accurately written "this only works at all if ...". – Stephen C Feb 14 '19 at 11:56
11

To answer your immutable question:

Collections.singletonList will create an immutable List. An immutable List (also referred to as an unmodifiable List) cannot have it's contents changed. The methods to add or remove items will throw exceptions if you try to alter the contents.

A singleton List contains only that item and cannot be altered.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
ajain
  • 444
  • 4
  • 7
3

If an Immutable/Singleton collections refers to the one which having only one object and which is not further gets modified, then the same functionality can be achieved by making a collection "UnmodifiableCollection" having only one object. Since the same functionality can be achieved by Unmodifiable Collection with one object, then what special purpose the Singleton Collection serves for?

Anonumous
  • 31
  • 1
  • Create an Unmodifiable Collection with one object the "normal" way and using the singleton method. Then you see immediately why. – kap Sep 03 '14 at 00:09
1

singletonList can hold instance of any object. Object state can be modify.

List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);

We can not define unmodifiableList like above.

Sarang
  • 422
  • 5
  • 11