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

Discussion

What will be the output of the program?

import java.util.*;

public class Sketch92
{
    public static void main(String[] args)
    {
        List<String> l = new ArrayList<String>(
            Arrays.asList("b", "a", "c"));
        String[] arr = l.toArray(new String[0]);
        Arrays.sort(arr);
        System.out.println(arr[0] + " " + l.get(0));
    }
}

  • A.The program prints b b
  • B.The program prints b a
  • C.The program prints a a
  • D.The program prints a b

Answer: D

toArray builds a new array holding the same references, so sorting it rearranges the array only and the list keeps its original order. The array starts with a while the list still starts with b. Nothing here is a view; the array and the list are independent containers.

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

Post your comment

Please log in or register to post a comment.