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

Discussion

Sample71 is run - what will be the output?

import java.util.*;
import java.util.concurrent.*;

public class Sample71
{
    public static void main(String[] args)
    {
        List<String> names = new CopyOnWriteArrayList<>(Arrays.asList("a", "b"));
        for (String s : names)
        {
            names.add("c");
            System.out.print(s);
        }
        System.out.print(" " + names.size());
    }
}

  • A.A ConcurrentModificationException after the first element
  • B.ab 2
  • C.ab 4
  • D.abc 4

Answer: C

The iterator works from a snapshot taken when iteration began, so it visits only a and b however many elements are added, and no ConcurrentModificationException is possible. The two additions do take effect, so the final size is four.

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

Post your comment

Please log in or register to post a comment.