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

假设我有一个List ,我知道我永远不想为它添加null 。 如果我向它添加null,则意味着我犯了一个错误。 所以每次我调用list.add(item)我会调用if (item == null) throw SomeException(); else list.add(item); if (item == null) throw SomeException(); else list.add(item); 。 是否有一个现有的List类(可能在Apache Commons或其他东西中)为我做这个?

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

注意 – 这里的几个答案声称通过包装列表并检入addaddAll来解决您的问题,但是他们忘记了您也可以通过其addAll添加到List 。 获得正确的约束列表很有挑战性,这就是为什么Guava有Constraints.constrainedList为你做的。

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

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

使用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规范说当集合不支持空值时应该抛出NullPointerException。 您可以使用以下包装器将function添加到任何Collection(您必须实现其他Collection方法以将它们委托给包装的实例):

 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); } ... } 

您可以通过包装List的实例并提供null检查的add方法来完成此操作。 换句话说,你的类只有几个方法和内部变量。

如果您需要列表的完整function,可以考虑使用Guava(以前是Google Collections) ForwardingList 。

另一种方法是扩展List,但问题是你需要覆盖addaddAll

有趣的是,guava有一个standardAddAll ,它可以用作addAll的实现,它至少解决了部分问题。

虽然这个问题有点叫“委托”,但是由于你打算inheritance几乎所有相同的function,因此子类化会更容易。

 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); } } 

这应该工作

 List list = Collections.checkedList(new ArrayList(), String.class); try { list.add(null); throw new AssertionError("Expected a NPE"); } catch (NullPointerException expected) { System.out.println("list.add(null); threw "+expected); } try { List list2 = Arrays.asList("", null); list.addAll(list2); throw new AssertionError("Expected a NPE"); } catch (NullPointerException expected) { System.out.println("list.addAll(\"\", null); threw " + expected); } 

但是,addAll实现中的错误意味着您需要使用以下内容

 List list = Collections.checkedList( Collections.checkedList(new ArrayList(), String.class), String.class); 

你明白了

 list.add(null); threw java.lang.NullPointerException list.addAll("", null); threw java.lang.NullPointerException 

尝试Collections.checkedList()。