是否有标准的 Java List 实现不允许向其添加 null? [英] Is there a standard Java List implementation that doesn't allow adding null to it?
问题描述
假设我有一个 List
并且我知道我永远不想向其中添加 null
.如果我向它添加 null ,则意味着我犯了一个错误.所以每次我要调用 list.add(item)
时,我都会调用 if (item == null) throw SomeException();否则 list.add(item);
.是否有现有的 List
类(可能在 Apache Commons 或其他东西中)为我执行此操作?
Say I have a List
and I know that I never want to add null
to it. If I am adding null to it, it means I'm making a mistake. So every time I would otherwise call list.add(item)
I would instead call if (item == null) throw SomeException(); else list.add(item);
. Is there an existing List
class (maybe in Apache Commons or something) that does this for me?
类似问题:Helper to remove null references in一个 Java 列表? 但我不想删除所有的空值,我想确保它们永远不会被添加到首位.
Similar question: Helper to remove null references in a Java List? but I don't want to remove all the nulls, I want to make sure they never get added in the first place.
推荐答案
注意——这里有几个答案声称可以通过包装列表并签入 add
和 addAll 来解决您的问题
,但他们忘记了您也可以通过 listIterator
添加到 List
.获得正确的受约束列表具有挑战性,这就是为什么 Guava 有 Constraints.constrainedList
为您做的原因.
Watch out -- several answers here are claiming to solve your problem by wrapping a list and checking in add
and addAll
, but they're forgetting you can also add to a List
via its listIterator
. It's challenging to get a constrained list right, which is why Guava has Constraints.constrainedList
to do it for you.
但在查看之前,首先考虑您是否只需要一个 immutable 列表,在这种情况下,Guava 的 ImmutableList
无论如何都会为您做空检查.如果您可以改用 JDK 的 Queue
实现之一,那也可以这样做.
But before looking at that, first consider whether you only need an immutable list, in which case Guava's ImmutableList
will do that null checking for you anyway. And in the off chance that you can use one of the JDK's Queue
implementations instead, that'll do it too.
(空敌对集合的好列表:https://github.com/google/guava/wiki/LivingWithNullHostileCollections)
(Good list of null-hostile collections: https://github.com/google/guava/wiki/LivingWithNullHostileCollections)
这篇关于是否有标准的 Java List 实现不允许向其添加 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!