I had a bunch of table views that had code duplicated in them. They used to directly inherit the AbstractView class. So then I made them inherit AbstractListView(Which would in it’s turn inherit from AbstractView) which would be the new class holding all the common properties for these tables.
Since I made that change this loop is behaving oddly:
for (AbstractViewPanel view : registeredViews) {
view.modelPropertyChange(evt);
}
Here is the arrayList: registeredViews:
private ArrayList<AbstractViewPanel> registeredViews;
I’ve run the debugger and the registeredViews arrayList has all of the views including the table ones. For some reason it stalls at the last directly inherited view in the collection and completely skips them.
All my views used to directly inherit:
public class someView extends AbstractViewPanel
Now since my change some of the views are like this:
public class someOtherView extends AbstractListView
Here’s AbstractListView:
public abstract class AbstractListView extends AbstractViewPanel
Here’s AbstractViewPanel
public abstract class AbstractViewPanel extends JPanel {
public abstract void modelPropertyChange(PropertyChangeEvent evt);
}
The loop is simply not going over anything that inherits AbstractListView, yet I would assume that all of the views in the end are of type AbstractView.
UPDATE
I’ve managed to find a workaround it simply involves changing the loop:
for (int i = 0; i < registeredViews.size(); i++)
{
registeredViews.get(i).modelPropertyChange(evt);
}
I would like to know though why the foreach style loop was giving me headaches.
For reference, I’ve created a skeleton sscce of your design.
List<E>implementsIterable<E>, so there’s no a priori reason yourforeachshould fail. Here are a few thing to check:Verify that GUI objects are constructed and manipulated only on the event dispatch thread.
Verify that you are not overlooking a
ClassCastExceptionwhen an instance ofSomeOtherViewis retrieved from theList.As the
Listis heterogenous, see Bloch, Effective Java 2nd ed., Item 29: Consider typesafe heterogeneous containers.” The pattern is mentioned here.Addendum: Would you not see a concurrent modification exception in that case?
No,
ConcurrentModificationException“does not always indicate that an object has been concurrently modified by a different thread.” The exception is thrown if the “list has been structurally modified” outside of the iterator, on a best-effort basis. More likely, the failing iterator was obtained after adding some views but before adding others. This could happen unexpectedly if the list were constructed on the initial thread and iterated on the EDT.SSCCE: