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

前端 未结 7 1852
傲寒
傲寒 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:28

    You might do this by just wrapping an instance of a List and providing the null-checked add method. In other words, your class would just have a couple of methods and in inner variable.

    If you need the full functionality of a list, you might consider Guava's (used to be Google Collections) ForwardingList.

    Another approach is to just extend List, but the gotcha there is that you need to override both add and addAll.

    Interestingly, guava has a standardAddAll, which can be used as the implementation of addAll, which solves at least part of the problem.

    0 讨论(0)
提交回复
热议问题