Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Map implementation with listeners for Java?

Tags:

java

I would like a Map implementation in which i could add listeners for put() events.

Is there anything like that in the standard or any 3rd party libraries?

like image 580
Julio Faerman Avatar asked Mar 23 '12 20:03

Julio Faerman


People also ask

What are the implementation of Map in Java?

The three general-purpose Map implementations are HashMap , TreeMap and LinkedHashMap .

Does Java Map implement collection?

Java has Iterable interface which is extended by Collection . The Collection is further extended by List , Queue and Set which has their different-different implementations but the unique thing notice is that the Map interface doesn't extend Collection interface.

How are listeners created in Java?

There is no built-in mechanism that would allow you to attach listeners to all variables. The object you want to watch needs to provide the support for that by itself. For example it could become Observable and fire off onChange events to its Observers (which you also have to ensure are being tracked).


2 Answers

I'm not aware of any standard or 3rd party, but it is easy, just create a class which wraps another Map and implements the Map interface:

public class MapListener<K, V> implements Map<K, V> {

    private final Map<K, V> delegatee;

    public MapListener(Map<K, V> delegatee) {
        this.delegatee = delegatee;
    }

    // implement all Map methods, with callbacks you need.

}
like image 82
Amir Pashazadeh Avatar answered Sep 17 '22 23:09

Amir Pashazadeh


Season to taste. This is representative, not normative. Of course it has issues.

public class ListenerMap extends HashMap {

    public static final String PROP_PUT = "put";
    private PropertyChangeSupport propertySupport;

    public ListenerMap() {
        super();
        propertySupport = new PropertyChangeSupport(this);
    }

    public String getSampleProperty() {
        return sampleProperty;
    }

    @Override
    public Object put(Object k, Object v) {
        Object old = super.put(k, v);
        propertySupport.firePropertyChange(PROP_PUT, old, v);
        return old;
    }

        public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.removePropertyChangeListener(listener);
    }
}
like image 32
Will Hartung Avatar answered Sep 17 '22 23:09

Will Hartung