我想在 java 中创建自己的 ArrayList 实现,它可以在列表发生变化时进行监听,并在发生这种情况时采取行动。 据我所读,我明白我不能扩展 ArrayList 然后添加监听器。
我想在类中使用 MyList 作为带有 public 修饰符的变量,这样用户可以直接更改它并在他更改它时完成操作。
class MyList extends ArrayList<object>.... { ... }
class UseOfMyList {
public MyList places = new MyList<Object>();
places.add("Buenos Aires");
//and to be able to do that
List cities = new ArrayList<Object>();
cities.add("Belmopan");
places = cities;
那么如何创建以及何时添加、删除或将另一个列表传递给 MyList 要执行的操作?
最佳答案
你不能通过扩展 ArrayList
来做到这一点,因为它没有内置的通知机制(而且,进一步,因为它已被声明为 final
因此不能扩展)。但是,您可以通过创建自己的 List
实现并针对 add()
和 remove()< 添加“监听器”功能来实现您想要的结果
方法:
class MyList<T>{
private ArrayList<T> list;
public MyList(){
list = new ArrayList<>();
...
}
public void add(T t){
list.add(t)
//do other things you want to do when items are added
}
public T remove(T t){
list.remove(t);
//do other things you want to do when items are removed
}
}
关于java - 如何在java中为ArrayList添加监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16529273/