I am making a GWT application and have to prevent client code from using null values in collections.
I found an answer but GWT doesn't support Queue
and its implementations as the GWT documentation says.
So, I had to make my own implementation.
import java.io.Serializable;
import java.util.ArrayList;
/**
* This implementation of {@link ArrayList} does not allow client code add null values
*
* @author Maxim Dmitriev
*
* @param <E>
*/
public class NonNullArrayList<E> extends ArrayList<E> implements Serializable {
private static final String NULL_VALUES_ARE_PROHIBITED = "Null values are prohibited";
private static final String CLONING_IS_UNSUPPORTED = "Cloning is unsupported. Please support if necessary";
public NonNullArrayList() {
// For serialization. super() is called automatically.
}
public NonNullArrayList(int initialCapacity) {
super(initialCapacity);
}
/**
*
*/
private static final long serialVersionUID = 7716772103636691126L;
public boolean add(E e) {
if (e == null) {
throw new IllegalArgumentException(NULL_VALUES_ARE_PROHIBITED);
}
return super.add(e);
};
public void add(int index, E element) {
if (element == null) {
throw new IllegalArgumentException(NULL_VALUES_ARE_PROHIBITED);
}
super.add(index, element);
};
public E set(int index, E element) {
if (element == null) {
throw new IllegalArgumentException(NULL_VALUES_ARE_PROHIBITED);
}
return super.set(index, element);
};
@Override
public Object clone() {
return new CloneNotSupportedException(CLONING_IS_UNSUPPORTED);
}
}
Besides I want to prevent client code from using the clone()
method because I just don't need it.
Is the implementation good or not?
Update #1
addAll()
's and the ArrayList(Collection<? extends E> c)
constructor don't need to throw NPEs
Update #2
Updated according to JohnMark13's and tintinmj's suggestions.
Update #3
CloneNotSupportedException
is not included in GWT. Supported classes.
@Override
public Object clone() {
return new UnsupportedOperationException(CLONING_IS_UNSUPPORTED);
}