Solved

Sorting objects by member fields

Posted on 2008-06-23
6
219 Views
Last Modified: 2010-03-30
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!
 
0
Comment
Question by:jchristn123
  • 3
  • 3
6 Comments
 
LVL 26

Accepted Solution

by:
ksivananth earned 500 total points
ID: 21852710
Use collection like List to store the Person obj and use Collections.sort with custom comparator...

for e.g.,

class PersonComparatorByName implements Comparator<Person>{
  public int compare( Person p1, Person p2 ){
    return p1.getPersonName().compareTo( p2.getPersonName() ) ;
  }
}

ArrayList<Person> persons = new ArrayList<Person>() ;
//populat the list with person objects
Collections.sort( persons, new PersonComparatorByName () ) ;
0
 
LVL 1

Author Comment

by:jchristn123
ID: 21852787
Do I need to manually create the compareTo method?
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 21852789
you need not, compareTo method already exists in String
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:jchristn123
ID: 21852808
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!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 21852818
List<Person> list = Arrays.asList( person ) ;
0
 
LVL 1

Author Comment

by:jchristn123
ID: 21862494
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
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
noX challenge 17 77
array11 challenge 16 52
countAbc challenge 9 50
Understanding websocket example in spring 1 43
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…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

743 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

12 Experts available now in Live!

Get 1:1 Help Now