Skip to content

Instantly share code, notes, and snippets.

@axemorgan
Created January 14, 2016 15:10
Show Gist options
  • Save axemorgan/0a885698003b380e6b58 to your computer and use it in GitHub Desktop.
Save axemorgan/0a885698003b380e6b58 to your computer and use it in GitHub Desktop.
An ArrayList implementation that does not accept null values. Attempts to add null to it result in an exception.
import java.util.ArrayList;
import java.util.Collection;
/**
* An {@link ArrayList} implementation that does not accept null values. Attempts to add
* <code>null</code> using any of the add methods will result in an {@link IllegalArgumentException}
* being thrown. Attempts to addAll from a Collection that contains null elements will also result
* in an exception.
* <p/>
* Here's why: <a href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained">UsingAndAvoidingNullExplained</a>
*/
public class NonNullArrayList<T> extends ArrayList<T> {
public NonNullArrayList() {
super();
}
public NonNullArrayList(int capacity) {
super(capacity);
}
public NonNullArrayList(Collection<? extends T> collection) {
super(collection);
for (T item : collection) {
if (item == null) {
throw new NullArgumentException();
}
}
}
@Override
public boolean add(T object) {
if (object != null) {
return super.add(object);
} else {
throw new NullArgumentException();
}
}
@Override
public void add(int index, T object) {
if (object != null) {
super.add(index, object);
} else {
throw new NullArgumentException();
}
}
@Override
public boolean addAll(Collection<? extends T> collection) {
for (T object : collection) {
if (object != null) {
this.add(object);
} else {
throw new NullArgumentException();
}
}
return super.addAll(collection);
}
@Override
public boolean addAll(int index, Collection<? extends T> collection) {
boolean changed = false;
for (T object : collection) {
if (object != null) {
add(index, object);
index++;
changed = true;
} else {
throw new NullArgumentException();
}
}
return changed;
}
private static final class NullArgumentException extends IllegalArgumentException {
public NullArgumentException() {
super("Cannot add null to a NonNullArrayList");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment