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

Discussion

What will be the output of the program?

import java.util.*;

public class Demo49
{
    public static void main(String[] args)
    {
        List<String> l = new ArrayList<String>(
            Arrays.asList("a", "b", "c"));
        List<String> view = l.subList(0, 2);
        view.set(0, "z");
        System.out.println(l);
    }
}

  • A.The program prints [z, b, c]
  • B.The program prints [z, b]
  • C.A ConcurrentModificationException is thrown.
  • D.The program prints [a, b, c]

Answer: A

Correct answer: The program prints [z, b, c]

subList returns a *view* onto the backing list, not a copy, so writing through the view writes through to the original: setting index 0 of the view sets index 0 of the list. Printing l therefore shows [z, b, c] - the whole list, with only the first element changed. The view is also fragile: structurally modifying the backing list through any other route invalidates it.

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

Post your comment

Please log in or register to post a comment.