Why traverse listener lists backwards?

J

J Krugman

Looking at Swing code I'm surprised that, invariable, when a list
of event listeners needs to be traversed, it is done from last to
first. Why is this?

Thanks,

jill
 
X

xarax

J Krugman said:
Looking at Swing code I'm surprised that, invariable, when a list
of event listeners needs to be traversed, it is done from last to
first. Why is this?

Unless the JavaDoc specifies the order in which listeners
are called, you cannot rely on the order (LIFO versus FIFO)
of calling listeners. Different vendors make provide
different implementations, and thus call the listeners in
a different order. So, do not design your listeners to
presume a certain order of calling, unless the JavaDoc
of the Swing API specifies a certain order.
 
J

Jacob

J said:
Looking at Swing code I'm surprised that, invariable, when a list
of event listeners needs to be traversed, it is done from last to
first. Why is this?

I don't know the specific case, but in general (as a pattern)
it is useful to traverse this kind of lists backwards in case
the accessed element is deleted along the way. A delete during
a traverse normally affects the remainder of the list, and a
forward iteration might easily be messed up.

As this makes assumptions about the implementation of the
underlaying structure, it is in general better to iterate over
a *copy* of the list.
 
T

Tor Iver Wilhelmsen

J Krugman said:
Looking at Swing code I'm surprised that, invariable, when a list
of event listeners needs to be traversed, it is done from last to
first. Why is this?

This allows later added listeners (that is, the developer's own
listeners) to e.g. consume the event, so that the default behaviour
can be superseded by the developer's code. If it was the other way
around, then the "standard" listeners would trigger first.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top