我想要檢測何時將某些項目添加到數組列表或從中刪除某些項目。其實我有一個像下面的一些代碼:定製arraylist與通知刪除並添加
public class myClass {
MyCustomArrayList<MyObject> al;
public void method1() {
al.add(myObject);
// Do other works
al.remove(myObject)
// Do other works
}
private void DoByEachAdd() {
//I want array list call this method by adding each item to it.
// It should be in this class because it is doing some works
// related to this class. for example changing some private variables
}
private void DoByEachRemove() {
// I want array list call this method by adding each item to it.
// It should be in this class too.
}
}
我知道,數組列表,並沒有對具有監聽或某種形式的通知或事件的能力,如果我想檢測加應該有一個自定義的數組列表。類似下面的類:
class MyArrayList<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
}
(我從here得到它)
所以現在的問題是:我怎麼能通知MyArrayList
(al
)對象調用DoByEachAdd
和DoByEachRemove
方法時remove
和方法被解僱。有些身體有任何想法嗎?