Search code examples
javalistenerstreemap

How to make a listener that listens for changes in a TreeMap?


I'm making a GUI which conjugates Spanish Verbs. It utilizes a TreeMap as the main data structure, which is filled with instantiations of the class Verb. Each instantiation includes a String which contains the infinitive form of the Verb, like "hablar" or "escribir." There's a function in the GUI that allows the user to input a new Verb by typing in its infinitive and its English translation.

I want to know how to create a listener that will run some code every time that a new verb is added -- or removed -- from the TreeMap. How would I go about doing this?


Solution

  • You can subclass the TreeMap class, eg.

    public class MyTreeMap<K, V> extends TreeMap<K, V> {
        @Override
        public V put(K key, V val) {
            V ret = super.put(key, val);
            myAddCallback(key, val);
            return ret;
        }
    
        @Override
        public V remove(K key) {
            V ret = super.remove(key);
            myRemoveCallback(key);
            return ret;
        }
    }
    

    Another (significantly more involved) option would be to check out AspectJ, an AOP-based JRE.