如何防止Java中的ArrayList删除元素? [英] How to prevent element deleting from ArrayList in Java?
问题描述
我想要一个 ArrayList
,并且还要限制元素提取。我该怎么办?
I want to have an ArrayList
, and to restrict element delinting as well. How can I do it?
推荐答案
在 List
界面上创建一个包装器这不允许删除,只需要删除所需的方法:
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
}
另一个不值得推荐的选择是从 ArrayList
扩展并覆盖删除
方法什么都不做,但它是不希望因为你不应该扩展这些类,除非确实需要:
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...
}
}
此外,您可以使用列表。 oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList%28java.util.List%29\">Collections#unmodifiableList
避免删除元素(这是上面提到的包装类,除了实现 List
),但请注意,你也不能添加元素。
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.
这篇关于如何防止Java中的ArrayList删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!