Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java code optimization when iterate list

It is common to iterate list of elements. Check some conditions and remove some elements from list.

for (ChildClass childItem : parent.getChildList()) {
    if (childItem.isRemoveCandidat()) {
    parent.getChildList().remove(childItem);    
    }
}

But in this case java.util.ConcurrentModificationException is thrown.

What is the best program pattern in this case?

like image 235
Balconsky Avatar asked Feb 19 '26 18:02

Balconsky


2 Answers

Use an Iterator. If your list supports Iterator.remove you can use it instead! It won't throw the exception.

Iteartor<ChildClass> it = parent.getChildList().iterator();
while (it.hasNext())
    if (it.next().isRemoveCandidat()) 
        it.remove();

Note: The ConcurrentModificationException is thrown when you have "started" iterating over a collection and modifies the list during the iteration time (eg in your case it doesn't have anything todo with concurrency. You are using the List.remove operation during the iteration and that is the same in this case..).


Full example:

public static void main(String[] args) {

    List<Integer> list = new LinkedList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);

    for (Iterator<Integer> it = list.iterator(); it.hasNext(); )
        if (it.next().equals(2))
            it.remove();

    System.out.println(list); // prints "[1, 3]"
}
like image 106
dacwe Avatar answered Feb 22 '26 09:02

dacwe


another option is:

for(int i = parent.getChildList().length - 1; i > -1; i--) {

    if(parent.getChildList().get(i).isRemoveCandidat()) {
        parent.getChildList().remove(i);
    }
}
like image 26
Tom Avatar answered Feb 22 '26 07:02

Tom