简体   繁体   中英

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.

PS 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM