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

前端 未结 7 1862
傲寒
傲寒 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:11

    AFAIK, there is no standard implementation available in the JDK. However, the Collection spec says that NullPointerException should be thrown when a collection does not support nulls. you can use the following wrapper to add the functionality to any Collection (you'll have to implement the other Collection methods to delegate them to the wrapped instance):

    class NonNullCollection implements Collection {
    
        private Collection wrapped;
        public NonNullCollection(Collection wrapped) {
            this.wrapped = wrapped;
        }
        @Override
        public void add(T item) {
            if (item == null) throw new NullPointerException("The collection does not support null values");
            else wrapped.add(item);
        }
        @Override
        public void addAll(Collection items) {
            if (items.contains(null)) throw new NullPointerException("The collection does not support null values");
            else wrapped.addAll(item);
        }
        ...
    }
    

提交回复
热议问题