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

前端 未结 7 1900
傲寒
傲寒 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:20

    Use Apache Commons Collection:

    ListUtils.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate());
    

    Adding null to this list throws IllegalArgumentException. Furthermore you can back it by any List implementation you like and if necessary you can add more Predicates to be checked.

    Same exists for Collections in general.

    Use Google Guava:

    Constraints.constrainedList(new ArrayList(), Constraints.notNull())
    

    Adding null to this list throws NullPointerException.

提交回复
热议问题