Java增强的for循环(对于每个循环)抛出异常 [英] Java enhanced for loop (for each loop) throws Exception

查看:600
本文介绍了Java增强的for循环(对于每个循环)抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议我使用List<JLabel> list = new ArrayList<class>收集并随后从我的JPanel

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();
}

这段代码给了我
线程"AWT-EventQueue-0"中的异常

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)

在线

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.

推荐答案

问题出在这里:

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

您不能遍历集合中的元素并同时从中删除元素,从而导致ConcurrentModificationException.改为执行此操作:

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();

这篇关于Java增强的for循环(对于每个循环)抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆