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

Discussion

What will be the output of the program?

import java.util.*;

public class Trial43
{
    public static void main(String[] args)
    {
        List<Integer> scores = new ArrayList<Integer>(
            Arrays.asList(70, 95, 82));
        Collections.sort(scores, Collections.reverseOrder());
        int top = scores.get(0);
        Collections.sort(scores);
        System.out.println(top + " " + scores.get(0) + " " + scores);
    }
}

  • A.70 95 [95, 82, 70]
  • B.70 70 [70, 82, 95]
  • C.95 70 [70, 82, 95]
  • D.95 95 [95, 82, 70]

Answer: C

reverseOrder returns a comparator that inverts the natural ordering, so the first sort puts the highest score first and top reads 95. Sorting again without a comparator restores ascending order, so the same position now holds 70. Each sort rearranges the list in place; nothing is returned.

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

Post your comment

Please log in or register to post a comment.