Java enhanced for loop (for each loop) throws Exception

做~自己de王妃 提交于 2020-06-29 03:46:46

问题


I was recommended to use a List<JLabel> list = new ArrayList<class> to collect and later remove a number of unspecific JLabel images from my JPanel

private List<JLabel> cardImages = new ArrayList<JLabel>();
public void addCardImage(BufferedImage img, boolean playerCard) {

        JLabel imgLabel = new JLabel();
        ImageIcon icon;
        icon = new ImageIcon(img);
        imgLabel.setIcon(icon);
        cardImages.add(imgLabel);
        if (playerCard)
            pCardPanel.add(imgLabel);
        else
            dCardPanel.add(imgLabel);
        display.pack();

    }
private void removeCards() {
    for (JLabel imgLabel : cardImages) {
        remove(imgLabel);
        cardImages.remove(imgLabel);
    }
    display.pack();
}

This code gives me
Exception in thread "AWT-EventQueue-0"

java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)

In the line

for (JLabel imgLabel : cardImages) {

(I don't know if this matters but the Game is runnable and is running on a thread.)
I copied the code as given to me in the answer and I don't see the problem, any ideas? Thanks in advance.


回答1:


Here's the problem:

for (JLabel imgLabel : cardImages) {
    remove(imgLabel);
    cardImages.remove(imgLabel); // not allowed!
}

You cannot iterate over the elements from a collection and remove elements from it at the same time, that results in a ConcurrentModificationException. Do this instead:

for (JLabel imgLabel : cardImages) {
    remove(imgLabel);
}
cardImages.clear();


来源:https://stackoverflow.com/questions/62458868/java-enhanced-for-loop-for-each-loop-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!