微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用迭代器从列表中删除条目

如何解决使用迭代器从列表中删除条目

代码无法编译。什么this.tokens

无论如何,如果要在迭代时删除元素,则必须使用迭代器的remove方法进行操作:

itr.next();
itr.remove();

不过,您的removeAllElements方法可以做到this.elements.clear()。更直接,更有效。

解决方法

我需要编写一个简单的函数,该函数将删除List包含类对象的所有条目Elem。我编写了函数removeAllElements,但是如果的大小List<Elem>大于1
,则该函数将不起作用。

public class Test {

public static void main(String[] args) {
        Work w = new Work();
        w.addElement(new Elem("a",new Integer[]{1,2,3}));
        w.addElement(new Elem("b",new Integer[]{4,5,6}));

        w.removeAllElements(); // It does not work for me.
    }
}

public class Work {

    private List<Elem> elements = new ArrayList<Elem>();

    public void addElement(Elem e) {
        this.elements.add(e);
    }

    public void removeAllElements() {
        Iterator itr = this.elements.iterator(); 
        while(itr.hasNext()) {
            Object e = itr.next();
            this.elements.remove(e);
        }
    }

}

public class Elem {

    private String title;
    private Integer[] values;

    public Elem(String t,Integer v) {
        this.title = t;
        this.values = v;
    }

}

编辑#1 错误消息如下:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
    at java.util.AbstractList$Itr.next(Unknown Source)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。