Search code examples
javaswingjtabletablemodelevent-queue

Why does fireTableChanged() on AbstractTableModel notify listeners last to first?


This is obscure, but for some reason the notification in AbstractTableModel is last-to-first, causing a bug in my code. I can fix it, but I'm wondering if anyone knows why notification is done in this way?

public void fireTableChanged(TableModelEvent e) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
        if (listeners[i]==TableModelListener.class) {
        ((TableModelListener)listeners[i+1]).tableChanged(e);
        }
    }
}

Solution

  • I don't think there is a real reason for it.

    Maybe they wanted extra-safety in case a listener is removes itself from the list of listeners while the event is fired (i.e. while we are still iterating over the listeners-list).

    Although this would not really be necessary as the listenerList is copy-on-write...