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

Discussion

What will be the output of the program?

import java.util.*;

public class Probe24
{
    public static void main(String[] args)
    {
        List<Integer> ticks = new ArrayList<Integer>(
            Arrays.asList(10, 30));
        ticks.add(1, 20);
        ticks.add(40);
        System.out.println(ticks + " last=" + ticks.get(ticks.size() - 1));
    }
}

  • A.[20, 10, 30, 40] last=40
  • B.[10, 30, 20, 40] last=40
  • C.[10, 20, 30, 40] last=30
  • D.[10, 20, 30, 40] last=40

Answer: D

The two-argument add inserts at the index and shifts everything from there one place right, so 20 lands between 10 and 30 without overwriting anything. The single-argument add appends, putting 40 at the end, which is what the last element reports. Each call grows the list by one.

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

Post your comment

Please log in or register to post a comment.