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

Discussion

What will be the output of the program?

import java.util.*;

public class Probe48
{
    public static void main(String[] args)
    {
        List<String> words = new ArrayList<String>(
            Arrays.asList("pear", "fig", "banana"));
        String longest = Collections.max(words, new Comparator<String>()
        {
            public int compare(String x, String y)
            {
                return x.length() - y.length();
            }
        });
        System.out.println(longest + " " + Collections.max(words));
    }
}

  • A.The program prints pear banana
  • B.The program prints banana banana
  • C.The program prints banana pear
  • D.The program prints pear pear

Answer: D

The first call supplies a comparator ranking by length, so it returns banana. The second uses the natural ordering of String, which is lexicographic, and p sorts after b and f, so it returns pear. Same collection, two different maxima, decided entirely by the ordering in force.

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

Post your comment

Please log in or register to post a comment.