-1

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)?

3
  • 2
    Have you considered using Collections.unmodifiableList? Commented Aug 7, 2017 at 14:28
  • 2
    "Better way" is a very vague expression here? How do you measure the goodness of the solution? Commented Aug 7, 2017 at 14:29
  • Thanks everyone to answers, but I need only forbid deleting, so Collections.unmodifiableList does not fit because it does not allow to modify the data Commented Aug 7, 2017 at 15:23

2 Answers 2

-2
public class NotRemovableArrayList<T> extends ArrayList<T> {
    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }

    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

"The question is what is the better way: extend of ArrayList or extend of AbstractList". And this is not the answer.
-2

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

"The question is what is the better way: extend of ArrayList or extend of AbstractList"
@ErwinBolwidt and? second part of the answer is particular addressing that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.