I want to have an ArrayList, and to restrict element delinting as well. How can I do it?
4 Answers
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.
2 Comments
List interface, so wrapper could be put in List<T> fields and it presence would be transparent.List interface (note the comment at bottom of my answer).Use the ImmutableList class from the google guava library.
BTW: this is a duplciate of: make ArrayList Read only
1 Comment
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;
}
}
ArrayListwhere you cannot ever delete an element from it? Why is this tagged asmagic?