Remove entries from the list using iterator

2020-02-14 07:11发布

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)

4条回答
男人必须洒脱
2楼-- · 2020-02-14 07:50

You must use itr.remove() and not this.tokens.remove(e) while removing elements while iterating.

For more details, look at Iterator.remove()

查看更多
够拽才男人
3楼-- · 2020-02-14 07:57

I am assuming that tokens is your Arraylist?

When removing elements dynamically from an array list, you need to use the .remove method provided by the iterator. So you need to do something like this:

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

If you want to just remove all the elements from the list, you can call the .clear method of the Arraylist:

Removes all of the elements from this list. The list will be empty after this call returns.

查看更多
爷、活的狠高调
4楼-- · 2020-02-14 08:05

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.

查看更多
霸刀☆藐视天下
5楼-- · 2020-02-14 08:13
登录 后发表回答