This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes array sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "array sorting" Watch "array sorting" New topic

array sorting

Jini Varghese
Ranch Hand

Joined: Dec 06, 2000
Posts: 58
How to sort an array in descending order ?
java.util.Arrays has methods that sorts in the ascending order. Do I have to use Comparator interface implementing the code for descending sort in its compare(), and pass the instance of the class that implements Comparator to sort() of Arrays class ?
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3527
You do not have to implement the code for descending sort. It is already done by Arrays class. What you need to do is implement a Comparator object having compare method which just compares the two objects and return appropriate results ( ie. -1 when o1 is greater than o2 etc.) Pass this comparator object as the second parameter to the sort() method.
Just implement compareTo() method in the class of objects that you want to sort. In this case you just have pass the array of objects.
Read Comparator, Arrays.sort() API for more details.
Get Certified, Guaranteed!
(Now Revised for the new Pattern)

Try out the world's only WebCompiler!

Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
Jini Varghese
Ranch Hand

Joined: Dec 06, 2000
Posts: 58
Thanks. It helped a lot...
I agree. Here's the link:
subject: array sorting
It's not a secret anymore!