Use of Java's Collections.singletonList()?

前端 未结 6 864
無奈伤痛
無奈伤痛 2021-01-29 18:58

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?

相关标签:
6条回答
  • 2021-01-29 19:15

    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. But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ...

    0 讨论(0)
  • 2021-01-29 19:19

    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.

    0 讨论(0)
  • 2021-01-29 19:21

    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.

    0 讨论(0)
  • 2021-01-29 19:23

    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.

    0 讨论(0)
  • 2021-01-29 19:28

    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?

    0 讨论(0)
  • 2021-01-29 19:35

    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.

    0 讨论(0)
提交回复
热议问题