Remove entries from the list using iterator

前端 未结 4 845
无人及你
无人及你 2020-12-21 09:30

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 remo

相关标签:
4条回答
  • 2020-12-21 09:48

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

    For more details, look at Iterator.remove()

    0 讨论(0)
  • 2020-12-21 09:50

    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.

    0 讨论(0)
  • 2020-12-21 09:51

    You have to call the iterator's "remove" method: http://www.java-examples.com/remove-element-collection-using-java-iterator-example.

    0 讨论(0)
  • 2020-12-21 09:55

    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.

    0 讨论(0)
提交回复
热议问题