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

Discussion

What will be the output of the program?

import java.util.*;

public class Program42
{
    static class Person
    {
        String name;
        Person(String name) { this.name = name; }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>(
            Arrays.asList(new Person("zoe"), new Person("amy")));
        Collections.sort(people);
        System.out.println(people.size());
    }
}

  • A.The program prints 2
  • B.Compilation fails, because Person is not Comparable.
  • C.A ClassCastException is thrown.
  • D.The program prints 0

Answer: B

Collections.sort requires its element type to extend Comparable, and the compiler enforces that through the method's generic signature, so this is rejected before it can run. The raw-typed equivalent from before generics would instead have compiled and thrown ClassCastException at runtime.

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

Post your comment

Please log in or register to post a comment.