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?
The three general-purpose Map implementations are HashMap , TreeMap and LinkedHashMap .
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.
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).
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.
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With