是否有标准的Java List实现,不允许向其添加null?

Mat*_*rog 25 java collections null list

说我有一个List,我知道我永远不想添加null它.如果我向它添加null,则意味着我犯了一个错误.因此,每次我打电话,list.add(item)我都会打电话if (item == null) throw SomeException(); else list.add(item);.是否存在List为我这样做的现有类(可能在Apache Commons或其他内容中)?

类似的问题:帮助删除Java列表中的空引用?但我不想删除所有空值,我想确保它们从未被添加到第一位.

Kev*_*ion 25

当心-在这里好几个答案都声称通过包装清单和检查,以解决您的问题addaddAll,但他们忘了,你也可以添加到List通过其listIterator.获得正确的约束列表具有挑战性,这就是为什么Guava必须Constraints.constrainedList为您做到这一点.

但在查看之前,首先要考虑一下你是否只需要一个不可变列表,在这种情况下,无论如何,Guava ImmutableList都会为你做空检查.而且,如果您不能使用JDK的其中一个Queue实现,那么它也会这样做.

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

  • 更新:自从Guava 16以来,"约束"已被删除 (7认同)
  • 新网址为:https://github.com/google/guava/wiki/LivingWithNullHostileCollections (2认同)

Fab*_*ney 16

使用Apache Commons Collection:

ListUtils.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate());
Run Code Online (Sandbox Code Playgroud)

将NULL添加到此列表将抛出IllegalArgumentException.此外,您可以通过任何您喜欢的List实现来支持它,如果需要,您可以添加更多要检查的谓词.

一般来说,集合也存在相同的情况.

使用Google Guava:

Constraints.constrainedList(new ArrayList(), Constraints.notNull())
Run Code Online (Sandbox Code Playgroud)

将NULL添加到此列表将抛出NullPointerException.


Rya*_*oss 5

AFAIK,JDK中没有可用的标准实现。但是,Collection规范指出,当collection不支持null时,应该引发NullPointerException。您可以使用以下包装器将功能添加到任何Collection中(您必须实现其他Collection方法以将它们委托给包装的实例):

class NonNullCollection<T> implements Collection<T> {

    private Collection<T> wrapped;
    public NonNullCollection(Collection<T> 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<T> items) {
        if (items.contains(null)) throw new NullPointerException("The collection does not support null values");
        else wrapped.addAll(item);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • @Steve Kuo:我只抛出 NullPointerException 因为这是 Collection javadoc 所说的如果 Collection 不支持 null 则抛出的异常。 (2认同)

Jer*_*emy 1

尽管这个问题有点像“委托”,但使用子类化会容易得多,因为您打算继承几乎所有相同的功能。

class MyList extends List {

  //Probably need to define the default constructor for the compiler

  public add(Object  item) {
    if (item == null) throw SomeException();
    else super.add(item);
  }    

  public addAll(Collection c) {
    if (c.contains(null)) throw SomeException();
    else super.addAll(c);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 请参阅上面我对尼克的评论。另外,我必须扩展一个像 ArrayList 这样的具体类,这意味着如果我以后需要一个不允许空值的 LinkedList,我将必须重新完成所有工作。所以我想,嗯,也许它应该只是一个包装现有列表的实用方法,有点像“Collections.unmodifyingList”。然后我想,等等,也许有人已经经历过这一切。 (4认同)