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

Discussion

What will be the output of the program?

import java.util.*;

public class Example41
{
    static class Person implements Comparable<Person>
    {
        String name;
        Person(String name) { this.name = name; }

        public int compareTo(Person other)
        {
            return name.compareTo(other.name);
        }

        public String toString() { return 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);
    }
}

  • A.The program prints [amy, zoe]
  • B.A ClassCastException is thrown.
  • C.Compilation fails.
  • D.The program prints [zoe, amy]

Answer: A

Collections.sort uses the natural ordering, which Person supplies by implementing Comparable, so the list is ordered by name and prints [amy, zoe]. Overriding toString is what makes the output readable; without it each element would print as a class name and a hash.

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

Post your comment

Please log in or register to post a comment.