What is the use of singletonList?

前端 未结 3 1174
予麋鹿
予麋鹿 2021-01-04 11:28

I was looking around for some elegant solution to removing null values from a List. I came across the following post, which says I can use list.removeAll(Collections.

3条回答
  •  耶瑟儿~
    2021-01-04 11:43

    It works like a charm:

    List list = new ArrayList();
    list.add("abc");
    list.add(null);
    list.add("def");
    list.removeAll(Collections.singletonList(null));
    System.out.println(list);  //[abc, def]
    

    Indeed Collections.singletonList(null) is immutable (which is unfortunately hidden in Java[1]), but the exception is thrown from your list variable. Apparently it is immutable as well, like in example below:

    List list = Arrays.asList("abc", null, "def");
    list.removeAll(Collections.singletonList(null));
    

    This code will throw an UnsupportedOperationException. So as you can see singletonList() is useful in this case. Use it when client code expects a read-only list (it won't modify it) but you only want to pass one element in it. singletonList() is (thread-)safe (due to immutability), fast and compact.

    [1] E.g. in scala there is a separete hierarchy for mutable and immutable collections and API can choose whether it accept this or the other (or both, as they have common base interfaces)

提交回复
热议问题