Link to home
Start Free TrialLog in
Avatar of jchristn123
jchristn123

asked on

Sorting objects by member fields

Hello,

I have a simple question about sorting an array of objects based on any one of the member variables contained within that object.  Assume I have:

public class Person {
  protected int personNumber;
  protected String personName;

  // and then some set/get methods
  // and toString methods etc
}

public class PersonTest {
  public static void main (String[] args) {
    Person person[]=new Person[10];
    // and some code to define all of the people

    // and then a call to sort by personNumber
    // print the object (toString)

    // and then a call to sort by personName
    // print the object (toString)
  }
}

Using Arrays.sort or Collections.sort (I'm a novice Java programmer, so please be patient with me), can someone provide me a simple example of how to sort by personNumber and how to sort by personName?  My reference texts are not providing me much of any usable assistance on the topic.

Also any links to very thorough documentation and examples online would be much appreciated.  Just looking for guidance on steps to take to do this.

Thanks!
 
ASKER CERTIFIED SOLUTION
Avatar of ksivananth
ksivananth
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jchristn123
jchristn123

ASKER

Do I need to manually create the compareTo method?
you need not, compareTo method already exists in String
Thanks - what if I've already created the objects like this:

person[someNumber] = new person(number, name);

How would I turn that into a person definition within the list?

Thanks!
List<Person> list = Arrays.asList( person ) ;
I was able to continue using Arrays.sort by using the index parameters, i.e. Arrays.sort(object, 1, n) where n is the upper array boundary.  Worked like a champ