Fire Event When ArrayList Element Modified
I am working on an Android class that contains an ArrayList of generic objects. I am looking to fire an event in this class whenever an element of said ArrayList is modified.
In an ideal world, the ArrayList itself should be a private member, and the class would contain the public methods to add/update/delete an element and everything would be all fine and dandy.
Unfortunately, the ArrayList is exposed as a public member, so it and its elements are being modified all over the place (application). Without rewriting a boat load of 开发者_开发技巧code and/or going on a wild goose chase in the code, I am hoping I can find way to trigger an event when ArrayList is modified in the class containing the list. Any ideas?
You can subclass ArrayList and trigger an action (call a callback for example) after some of it's methods were invoked.
Then replace the original ArrayList in your Android class with your implementation.
P.S. Example:
public class MyArrayList<E> extends ArrayList<E> {
@Override
public boolean add(E object) {
// Do some action here
return super.add(object);
};
@Override
public void add(int index, E object) {
super.add(index, object);
// Do some action here
};
@Override
public E remove(int index) {
// Do some action here
return super.remove(index);
}
// etc...
}
Since it subclasses ArrayList you won't get any errors in your code, and everything that worked before, will work without any changes. With a little creativity the class can be made more elegant and efficient, but the general idea is there.
Edit: Yep. Sorry, was a little hasty with those returns. Fixed, and thanks Petar
精彩评论