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);
}
}
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.
Please log in or register to report this question.