天道酬勤,学无止境

How to prevent element deleting from ArrayList in Java?

I want to have an ArrayList, and to restrict element delinting as well. How can I do it?

标签

评论

Create a wrapper over List interface that doesn't allow removal, just the desired methods:

class MyArrayList<T> {
    private List<T> list;

    public MyArrayList() {
        list = new ArrayList<T>();
    }

    public boolean add(T t) {
        return list.add(t);
    }
    //add other desired methods as well
}

Another non recommendable option is to extend from ArrayList and override remove method(s) to do nothing, but it is not desired because you should not extend from these classes unless it is really needed:

public MyArrayList<T> extends ArrayList<T> {
    @Override
    public boolean remove() {
        //do nothing...
    }
}

Also, you could wrap your current List using Collections#unmodifiableList to avoid elements removal (that is a wrapper class like mentioned above except that implements List) but note that you cannot add elements either.

Create a subclass of ArrayList and override the remove methods.

If you want to forbid all modifications use Collections.unmodifiableList.

Use the ImmutableList class from the google guava library.

BTW: this is a duplciate of: make ArrayList Read only

You can create your own class extending ArrayList with will block all remove methods like in example

public class NoDeleteArray extends ArrayList{

    @Override
    public boolean remove(Object o) {
        return super.remove(o); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean removeAll(Collection c) {
        return false;
    }

    @Override
    public Object remove(int index) {
        return null;
    }

    @Override
    protected void removeRange(int fromIndex, int toIndex) {

    }

    @Override
    public boolean retainAll(Collection c) {
         return false;
    }

}

here all remove methods are covering original methods and does nothing. you can also perform some verification to check if object can be deleted from collection for example

@Override
public Object remove(int index) {
    MyClass tmp = (MyClass) get(index);
    if (tmp.isDeletable()) {
        return super.remove(index);
    } else {
        return null;
    }
}

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐