I want to implement ArrayList which is would not allow to user (or program) to delete elements from it. I want to keep rest of functionality of ArrayList. The question is what is the better way: extend of ArrayList or extend of AbstractList and how to forbid deleting (shadowing for example)?
2 Answers
public class NotRemovableArrayList<T> extends ArrayList<T> {
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
...
}
1 Comment
Erwin Bolwidt
"The question is what is the better way: extend of ArrayList or extend of AbstractList". And this is not the answer.
Common approach is to throw UnsupportedOperationException
in method's implementation. Throw this exception
from method that will not be used but
they are part of used public API.
If you want to totally implement all the methods
then you should use List interface.
Otherwise - use provided abstract variant or
directly extend from desired implementation
and override default behavior.
2 Comments
Erwin Bolwidt
"The question is what is the better way: extend of ArrayList or extend of AbstractList"
Izbassar Tolegen
@ErwinBolwidt and? second part of the answer is particular addressing that.
Collections.unmodifiableList?