Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

How will you efficiently remove elements while iterating a Collection?

Pragya Keshap answered on February 4, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • What is the difference between remove() method of Collection and remove() method of Iterator?

  • How will you efficiently remove elements while iterating a Collection?

    0

    The right way to remove elements from a collection while iterating

    is by using ListIterator.remove() method.

    E.g.

    ListIterator iter = myList.iterator();

    while(iter.hasNext()) {

    itr.remove();

    }

    Some developers use following code to remove an element which is

    incorrect:

    Iterator iter = myList.iterator();

    while(iter.hasNext()) {

    itr.remove();

    }

    By doing so we get ConcurrentModificationException.

    An iterator is first created to traverse the list. But at the same time

    the list is changed by remove() method.

    In Java, it is not allowed for a thread to modify a collection while

    another thread is iterating it. ListIterator provides the capability of

    removing an object during traversa

    Popularity 1/10 Helpfulness 1/10 Language java
    Source: Grepper
    Tags: elements java
    Link to this answer
    Share Copy Link
    Contributed on Feb 04 2023
    Pragya Keshap
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.