How to add listener on ArrayList in java
You're not going to be able to do this by extending ArrayList
, as it has no built-in notification mechanism (and, further, because it is has been declared final
and thus cannot be extended). However, you can achieve your desired result by creating your own List
implementation and adding your "listener" functionality vis a vis the add()
and remove()
methods:
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
}
}