【问题标题】:Remove entries from the list using iterator使用迭代器从列表中删除条目
【发布时间】:2012-02-12 02:29:06
【问题描述】:

我需要编写一个简单的函数来删除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)

【问题讨论】:

    标签: java list arraylist


    【解决方案1】:

    在迭代时移除元素时,您必须使用itr.remove() 而不是this.tokens.remove(e)

    更多详情请关注Iterator.remove()

    【讨论】:

    • 然后它说:线程“AWT-EventQueue-0”中的异常 java.lang.IllegalStateException at java.util.AbstractList$Itr.remove(Unknown Source) at cpn_logic.Work.removeAllElements(Work. java:119)
    • @KlausosKlausos:您需要在使用next() 后使用remove(),正如我链接到的javadocs 明确指出的那样。
    • 不只是应该,你必须
    • 哦,我不得不使用 itr.next() 和 itr.remove()
    【解决方案2】:

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

    无论如何,如果你想在迭代时移除一个元素,你必须使用迭代器的 remove 方法:

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

    不过,您的 removeAllElements 方法可以只执行 this.elements.clear()。更加直接和高效。

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        我假设 tokens 是您的 Arraylist?

        从数组列表中动态删除元素时,需要使用迭代器提供的.remove方法。所以你需要做这样的事情:

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

        如果你只想删除列表中的所有元素,可以调用Arraylist的.clear方法:

        从此列表中删除所有元素。该列表将为空 在此调用返回之后。

        【讨论】:

          猜你喜欢
          • 2013-11-25
          • 2014-10-26
          • 2016-10-23
          • 1970-01-01
          • 2013-10-05
          • 2020-05-27
          • 2016-07-19
          • 2015-08-21
          相关资源
          最近更新 更多