Why are listener lists (e.g. in Java those that use addXxxListener() and removeXxxListener() to register and unregister listeners) called lists, and usually implemented as Lists? Wouldn’t a Set be a better fit, since in the case of listeners there’s
- No matter in which order they get called (although there may well be such needs, but they’re special cases; ordinary listener mechanisms make no such guarantees), and
- No need to register the same listener more than once (whether doing that should result in calling the same listener 1 times or N times, or be an error, is another question)
Is it just a matter of tradition? Sets are some kind of lists under the hood anyway. Are there performance differences? Is iterating through a List faster or slower than iterating through a Set? Does either take more or less memory? The differences are certainly almost negligible.
One important reason for listener lists to be lists (instead of sets) also explains why you often see them being iterated through backwards. A common scenario involves a listener removing itself as a listener when it’s notified of some change. If the listeners were stored as a list and iterated forward (or stored as a set and iterated in some undetermined order), removing itself as a listener will cause a ConcurrentModificationException.
So, instead, the listeners are stored as a list and notified in backwards order. Then, if a listener removes itself from the list of listeners when it is notified, it does not cause a ConcurrentModificationException or shift the indices of the other not-yet-notified listeners.