Is there a standard Java List implementation that doesn't allow adding null to it?

前端 未结 7 1889
傲寒
傲寒 2020-12-09 02:31

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

7条回答
  •  臣服心动
    2020-12-09 03:26

    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.

    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.

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

提交回复
热议问题