Help Explain Java Function

Posted on 2011-10-22
Last Modified: 2012-05-12
Can someone please do two things for me.

import java.util.Arrays;

class Person implements Comparable<Person> {
  public Person(String firstName, String surname) {
    this.firstName = firstName;
    this.surname = surname;
  public String toString() {
    return firstName + " " + surname;
  public int compareTo(Person person) {
    int result = surname.compareTo(person.surname);
    return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;
  private String firstName;
  private String surname;
public class MainClass {
  public static void main(String[] args) {
    Person[] authors = { new Person("A", "B"), 
                         new Person("C", "D"),
                         new Person("E", "F"), 
                         new Person("Z", "Y"),
                         new Person("X", "T"), 
                         new Person("O", "R") };
    System.out.println("\nThe cast is ascending sequence is:\n");
    for (Person person : authors) {

Open in new window

1) Tell me when does the compareTo function get called? Because Comparable is implemented, does it automatically get ran when the Person class is initiated?

2) Rewrite the line:

return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;

to a more simplified if statement

Question by:InquisitiveProgrammer
    LVL 2

    Accepted Solution

    1) Arrays.sort(authors); calls compareTo() on the Objects in the array.  compareTo()  is not called when the the Object is instantiated.

    if (result ==0) {
        result = firstName.compareTo(person.firstName);
    return result;
    LVL 1

    Author Comment

    How does the program know not to use the generic Arrays.sort method?
    LVL 47

    Expert Comment

    What do you mean by generic Arrays.sort method ?

    I think your invocation

    corresponds only to this method
    public static void sort(Object[] a)[]%29

    LVL 1

    Author Comment

    What I mean is, how does the line


    know to call the compareTo function of the Person class
    LVL 47

    Expert Comment

    Well, it looks at your array - it figures out that your array is composed of objects of the type Person
    and uses Person's compareTo function.
    that is something which is called polymorphism in Java -
    when a method is invoked on the object, then the method corresponding to
    the actual type of the instance is invoked (basically method corresponding to new command
    which was used to construct this instance) is invoked, not the method of its parent.

    It is like this:

    class A {

    public void method(){
    //some stuff


    class B extends A {

    public void method() {
    // another stuff


    class TestPolymorphism {

    public static void main(String [] args){

    A a = new A();

    A b = new B();


    // at this point if you invoke method b.method() then   //another stuff   will be exected from overriden method of subclass
    // not the method of superclass, even though you declared b as belonging to type A
    // the method corresponding to creation of b with new B() operator will work
    //this is called polymorphism; it applies only to methods; variables of inherited classes behave differently



    Therefore even though sort method expects Objects it will recognize that your objects are in fact Persons
    at the time when it needs to invoke their

    read more about polymorphism here:

    LVL 2

    Expert Comment

    All elements in the array must implement the Comparable interface which forces your objects to have the compareTo(Object) method implemented.
    The sort will cast each element of the array as a Comparable and call compareTo(Object) to order the array.  This is a snippet from the Arrays class:
                for (int i=low; i<high; i++)
                    for (int j=i; j>low &&
                       ((Comparable)dest[j-1]).compareTo((Comparable)dest[j]) > 0; j--)
                          swap(dest, j, j-1);

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Hire Top Freelancers to Complete Java Projects

    Source the talented Expert Exchange community
    for top quality work on your Java projects.

    Hire the best. Collaborate easily. Get quality work.

    Suggested Solutions

    Title # Comments Views Activity
    Java MSI Solution 3 51
    maxMirror challenge 10 68
    SPLUNK REST  API call to Splunk to create and index? 2 39
    changeXy challenge 13 40
    Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
    Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
    Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
    Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now