Tutorial :How do I sort an array of Person Objects by using compareto()?



Question:

Here is my code:

> import java.util.Scanner;    import java.util.Arrays;      /**    This class tests the Person class.    */    public class PersonDemo     {      public static void main(String[] args)      {      int count = 0;      Scanner in = new Scanner(System.in);        boolean more = false;      Person first = null;      Person last = null;      while (more)      {        System.out.println(            "Please enter the person's name or a blank line to quit");        String name = in.nextLine();          if (name.equals(""))         more = false;        else        {         Person p = new Person(name); //new person object created with inputted name           Person[] people = new Person[10]; //new array of 10 person objects         people[count] = p; //declare person object with index of variable count as the new person object                                       first = people[count];  // I have no idea what to do here.  This is where I'm stuck.         last = people[count];   // I can't figure out what to do with this either.           first.compareTo(p); //call compareTo method on first and new person object         last.compareTo(p);  //call compareTo method on last and new person object                count++; // increase count variable        }       }          System.out.println("First: " + first.toString());         System.out.println("Last: " + last.toString());       }     }  

And the Person class:

/**    A person with a name.  */  public class Person implements Comparable    {   /**    * Constructs a Person with a name.    * @param aName the person's name    */   public Person(String aName)   {    name = aName;   }     public String getName()   {    return name;   }     @Override   public int compareTo(Object otherObject)    {    Person other = (Person)otherObject;    if (name.compareTo(other.name) < 0) return -1;    if (name.compareTo(other.name)  > 0) return 1;      return 0;   }     /**          Returns a string representation of the object.          @return name of Person   */   public String toString()   {    return "[name=" + name + "]";     }     private String name;     }  


Solution:1

What you are actually missing is that compareTo is a functionality that you give to objects. In your example you give a Person instance the capability of being compared with other Person to achieve a total ordering of the elements of that class.

Usually this method is implictly used by JDK collections like Lists, SortedMaps and so on but you have an array, that is a sort of primitive type, so you should look at Arrays.sort(Object[]) which will take care about ordering it using the Comparable interface.

A hint: since your compareTo method just work on the String of the Person you can easily just return its value instead of checking it to behave in the same way.


Solution:2

First off, get your array creation outside the loop. Second, even if the homework assignment said they'll only enter 10 names, you should assume more - you're just asking for IndexOutOfBoundsExceptions there. Consider using a collection like TreeSet which sorts automatically.

To sort an array:

Person[] people = new Person[10];  // add elements to the array...  java.util.Arrays.sort(people);  first = people[0];  // etc...  

To sort a Collection (a Set is a Collection without duplicates) just use TreeSet and they're sorted automatically.

TreeSet<Person> people = new TreeSet<Person>(); // using generics to say "only Person objects are allowed"  while (more) {      System.out.println("Please enter the person's name or a blank line to quit");      String name = in.nextLine();        if (name.equals(""))          more = false;      else          people.add(new Person(name));  }    System.out.println("First: " + people.first());   System.out.println("Last: " + people.last());  


Solution:3

Well, first of all, your code won't do much of anything until you set more to true initially. Otherwise, you'll just get a null pointer exception when you try to call tostring on a null object.

Also, don't create the person array within the while loop, otherwise it will be reset every time, and defeat what seems to be the purpose of storing all of the people.

Also, given to objects foo and bar, of the zoo class, you can't just do:

foo.compareto(bar);  

That would be like just having a line of code like

-4;  

Java doesn't like it.

So, to answer your question, using compare to methods, are like preform truth tests. For example

if(foo<bar)       /*Do something*/;  

Except, you can use .compareto() so that your actually comparing objects, rather than simply the references. So, you can determin which object of type zoo is greater, foo or bar, by comparing them with compare to. The API for compareto stipulates that if 0 is returned, their equal, if a positive number is returned, the first is greater, and if a negative number is returned, the second is greater. So:

if(foo.compareto(bar) >0)      /* foo is greater*/;  else if(foo.compareto(bar) = 0)      /* foo and bar are equal*/;  else      /* bar is greater*/;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »