Sorting a collection
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   varun_shastr
Posted On:   Friday, May 21, 2004 12:39 PM

I have a class Class Record { String FirstName; String LastName; } Class Directory { Record[] records; int numOfRecords; } I need to to sort records by FirstName.Can I use any built in or do I need to write my own sorting function!!! If I use Collections.sort(records, new Comparator()....) this will not work right??? Anybody can guide me in the rigth direction???    More>>


I have a class



Class Record {

String FirstName;

String LastName;

}



Class Directory {

Record[] records;

int numOfRecords;

}




I need to to sort records by FirstName.Can I use
any built in or do I need to write my own sorting function!!!


If I use

Collections.sort(records, new Comparator()....)

this will not work right???


Anybody can guide me in the rigth direction???

   <<Less

Re: Sorting a collection

Posted By:   varun_shastr  
Posted On:   Sunday, May 23, 2004 08:34 AM

Thank you !! I got it to work with Arrays.sort().

how can I make Record[] records to be a dynamic array?

I do not know the size of the records array and it

keeps changing as more records are added!!

Re: Sorting a collection

Posted By:   Sean_Owen  
Posted On:   Friday, May 21, 2004 01:13 PM

Yes, you are on the right track. You need to use a different but similar method, java.util.Arrays.sort(), to sort an array.



The sort() has to understand how two Record objects compare to each other. So, either Record must implement the Comparable interface, or else you need to implement a Comparator that can compare two Records. In either case, you will return the result of comparing FirstName from two Record objects.



See the javadoc for Comparable and Comparator for details.

About | Sitemap | Contact