Use of Java's Collections.singletonList()?

前端 未结 6 957
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题