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
当心-在这里好几个答案都声称通过包装清单和检查,以解决您的问题add和addAll,但他们忘了,你也可以添加到List通过其listIterator.获得正确的约束列表具有挑战性,这就是为什么Guava必须Constraints.constrainedList为您做到这一点.
但在查看之前,首先要考虑一下你是否只需要一个不可变列表,在这种情况下,无论如何,Guava ImmutableList都会为你做空检查.而且,如果您不能使用JDK的其中一个Queue实现,那么它也会这样做.
(null-hostile集合的良好列表:https://github.com/google/guava/wiki/LivingWithNullHostileCollections)
Fab*_*ney 16
使用Apache Commons Collection:
ListUtils.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate());
将NULL添加到此列表将抛出IllegalArgumentException.此外,您可以通过任何您喜欢的List实现来支持它,如果需要,您可以添加更多要检查的谓词.
一般来说,集合也存在相同的情况.
使用Google Guava:
Constraints.constrainedList(new ArrayList(), Constraints.notNull())
将NULL添加到此列表将抛出NullPointerException.
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);
    }
    ...
}
尽管这个问题有点像“委托”,但使用子类化会容易得多,因为您打算继承几乎所有相同的功能。
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);
  }
}