Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which line contains the error?

import java.util.*;

public class Sample58
{
    public static void main(String[] args)
    {
        List<String> l = new ArrayList<String>(Arrays.asList("a", "b"));
        for (String s : l)
        {
            assert s != null;
            if (s.equals("a")) l.remove(s);
        }
    }
}

  • A.No line here is in error.
  • B.if (s.equals("a")) l.remove(s);
  • C.assert s != null;
  • D.List l = new ArrayList(Arrays.asList("a", "b"));

Answer: B

Removing from a list while iterating it with a for-each throws ConcurrentModificationException on the next step. The assertion is fine and unrelated. Removal during iteration is done through the Iterator's own remove method, or by collecting the doomed elements and removing them afterwards.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.