使用迭代器列表中删除条目 [英] Remove entries from the list using iterator

查看:166
本文介绍了使用迭代器列表中删除条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个简单的函数,将删除列表包含类的对象ELEM 。我写的函数 removeAllElements ,但它不工作,如果的列表&LT规模; ELEM> 大于1

 公共类的测试{公共静态无效的主要(字串[] args){
        工作W =新作();
        w.addElement(新ELEM(一,新的整数[] {1,2,3}));
        w.addElement(新ELEM(b的,新的整数[] {4,5,6}));        w.removeAllElements(); //它不为我工作。
    }
}公共类工作{    私人列表<&ELEM GT;元素=新的ArrayList<&ELEM GT;();    公共无效的addElement(ELEM E){
        this.elements.add(E);
    }    公共无效removeAllElements(){
        迭代器ITR = this.elements.iterator();
        而(itr.hasNext()){
            对象E = itr.next();
            this.elements.remove(E);
        }
    }}公共类ELEM {    私人字符串称号;
    私人整数[]值;    公共ELEM(串T,整数v){
        this.title = T;
        this.values​​ = V;
    }}

编辑#1
该错误消息是:

 异常螺纹AWT-EventQueue的-0java.util.ConcurrentModificationException
    在java.util.AbstractList中的$ Itr.checkForComodification(来源不明)
    在java.util.AbstractList中的$ Itr.next(来源不明)


解决方案

在code不能编译。什么是 this.tokens

无论如何,如果你想删除,而迭代的元素,您必须使用迭代器的remove方法做到这一点:

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

removeAllElements 方法可能只是做 this.elements.clear(),虽然。更直接和有效的。

I need to write a simple function that will delete all entries in the List that contains objects of the class Elem. I wrote the function removeAllElements, but it does not work if the size of the List<Elem> is greater than 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;
    }

}

Edit#1 The error message is the following:

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)

解决方案

The code doesn't compile. What is this.tokens?

Anyway, if you want to remove an element while iterating, you must do it using the iterator's remove method:

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

Your removeAllElements method could just do this.elements.clear(), though. Much more straightforward and efficient.

这篇关于使用迭代器列表中删除条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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