Is there a Map implementation with listeners for Java?

前端 未结 4 1452
小鲜肉
小鲜肉 2021-02-19 14:01

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?

4条回答
  •  时光取名叫无心
    2021-02-19 14:11

    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);
        }
    }
    

提交回复
热议问题