singletonList的用途是什么? [英] What is the use of singletonList?
问题描述
我一直在寻找一些优雅的解决方案,以从列表中删除空值.我遇到了后续帖子,该帖子说我可以使用list.removeAll(Collections.singletonList(null));
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.singletonList(null));
但是,这引发了UnsupportedOperationException
,我认为这是因为removeAll()
试图对不可变的单例集合进行某些变数运算.这是正确的吗?
This, however, throws an UnsupportedOperationException
, which I'm assuming is because removeAll()
is attempting to do some mutative operation on the immutable singleton collection. Is this correct?
如果是这种情况,此singletonList
的典型用法是什么?当您确定不想对集合进行任何操作时,要表示大小为1的集合吗?
If this is the case, what would be a typical use of this singletonList
? To represent a collection of size 1 when you're sure you don't want to actually do anything with the collection?
谢谢.
推荐答案
它的工作原理就像是一种魅力:
It works like a charm:
List<String> list = new ArrayList<String>();
list.add("abc");
list.add(null);
list.add("def");
list.removeAll(Collections.singletonList(null));
System.out.println(list); //[abc, def]
实际上Collections.singletonList(null)
是不可变的(不幸的是,它隐藏在Java [1] 中),但是从您的list
变量抛出了异常.显然,它也是不可变的,如下面的示例所示:
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<String> list = Arrays.asList("abc", null, "def");
list.removeAll(Collections.singletonList(null));
此代码将抛出UnsupportedOperationException
.因此,您可以看到singletonList()
在这种情况下很有用.当客户端代码需要只读列表(不会修改它)而您只想在其中传递一个元素时,请使用它. singletonList()
是(线程)安全的(由于不可变),快速且紧凑.
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] 例如在 scala 的问题中,存在一个可变且不可变的独立层次结构集合和API可以选择是否接受一个或另一个(或两者都接受,因为它们具有通用的基本接口)
[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)
这篇关于singletonList的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!