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