| preferred AP College board partner for AP classes
hard Solved by 2 students
Java ArrayList Concurrent Modification
< Prev
Next >

What potential runtime error is present in the removeIfCondition method of the code segment shown?

import java.util.*;

public class IteratorIssue {
    private List<Integer> list = new ArrayList<>();
    
    public void removeIfCondition() {
        if(!list.isEmpty()) {
            for(Integer num : list) {
                if(num < 5) {
                    list.remove(num);
                }
            }
        }
    }
    
    public void addValue(int value) {
        list.add(value);
    }
    
    public static void main(String[] args) {
        IteratorIssue ii = new IteratorIssue();
        ii.addValue(3);
        ii.addValue(7);
        new Thread(() -> ii.removeIfCondition()).start();
    }
}
A

The for-each loop automatically synchronizes on the list, negating any potential issues.

B

The issue arises from a race condition between addValue and removeIfCondition, which is guaranteed by the unsynchronized if check.

C

The if statement’s early check makes the loop iterate over an empty collection, so no removal occurs.

D

Removing elements from an ArrayList while iterating over it without proper synchronization can lead to ConcurrentModificationException or unpredictable behavior.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy