Arkasha
Arkasha

Reputation: 117

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?

Upvotes: 1

Views: 2319

Answers (4)

T.G
T.G

Reputation: 1921

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;
    }
}

Upvotes: 0

rogergl
rogergl

Reputation: 3771

Use the ImmutableList class from the google guava library.

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

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 6

Joni
Joni

Reputation: 111269

Create a subclass of ArrayList and override the remove methods.

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

Upvotes: 3

Related Questions