是否有标准的Java List实现,不允许向它添加null? [英] Is there a standard Java List implementation that doesn't allow adding null to it?

查看:136
本文介绍了是否有标准的Java List实现,不允许向它添加null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有列表,我知道我永远不想添加 null 。如果我向它添加null,则意味着我犯了一个错误。所以每次我打电话给 list.add(item)我会调用 if if(item == null)抛出SomeException(); else 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?

类似的问题:帮助删除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.

推荐答案

注意 - 这里的几个答案声称通过包装列表并检入添加 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.

(null-hostile集合的良好列表: https://github.com/google/guava/ wiki / LivingWithNullHostileCollections

(Good list of null-hostile collections: https://github.com/google/guava/wiki/LivingWithNullHostileCollections)

这篇关于是否有标准的Java List实现,不允许向它添加null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆