Skip to content
Advertisement

How to properly add a value change listener to Map.Entry?

A project im working on currently requires me to ensure that while looping through a map’s entries, if Entry.setValue is called, it would trigger a value change event. I see I can try something like adding a listener into an extension of the Map class on the .put method. My question is, would entries being changed trigger a listener in the map’s put method? Or would I be forced to extend the Map.Entry class and stick listener logic into its setValue method?

Apologies in advance if this question is dumb – im new to using Maps in this way and a lot of the information ive seen so far has only lead to extending the Map itself, which seems easiest but i dont know if it would cover my case.

Advertisement

Answer

In a pinch you could use the PropertyChangeSupport class. It makes managing propertyChanges very easy. There’s not much to tell here. The parties that want to listen for changes register their listener with the map. Then when the map modifies the value, the support fires off an event to all the listeners. The values that are returned in the Event class may be altered to ones chosing.

JavaScript

Prints

JavaScript

A listener for demonstration.

JavaScript

The modified class

JavaScript

Note: There may be issues that have been missed in this simple solution. Testing should be conducted before put into production use. For one, there are many different ways to set an Entry's value. This only does it when put is invoked, either by the user or indirectly by the map itself.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement