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

Discussion

What will be the output of the program?

import java.util.*;

public class Sketch69
{
    public static void main(String[] args)
    {
        List<String> months = new ArrayList<String>(
            Arrays.asList("jan", "feb", "mar", "apr", "may", "jun"));
        months.subList(1, 4).clear();
        System.out.println(months + " size " + months.size());
    }
}

  • A.[jan, may, jun] size 3
  • B.[feb, mar, apr] size 3
  • C.An UnsupportedOperationException is thrown.
  • D.[jan, feb, mar, apr, may, jun] size 6

Answer: A

A subList is a view onto the backing list, so clearing it deletes that range from the original. The half-open bounds take positions 1, 2 and 3, which are feb, mar and apr, leaving three months. This is the documented idiom for removing a range in a single statement.

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

Post your comment

Please log in or register to post a comment.