![]() |
Sort java objects in an Array
I have an array of Java objects(for example: Employee). I need to sort this array based on any one of the data variable(for example: emp_name, desg, salary) in the Java class.
I had done using Comparable and Comparator interfaces. But the problem here is need to handle both ascending and descending dynamically based on parameter passed. Can anyone help me in this? Thanking you in advance. |
You're on the right track, you have to use compareTo inside your Comparator class that you create.
you have to have the compare( ) method this is where how you want to sort it. |
I think this code might be helpful
Code:
|
Solution: Dynamic variable can be passed to determine the the sorting order
Dynamic variable can be passed to determine the the sorting order
Please find the updated sample code. Thanks [PHP]Sample code: Camparable Object: PHP Code:
PHP Code:
|
Quote:
Quote:
|
Quote:
|
You guys are thinking too hard :P
There are tons of ways to do this, from creating you're own sorts, you're own collections, and so forth. But the easiest ways are already built in. You need to implement a Comparable interface (I'm using generics here, but you can do this without and using 1.4), and make use of the Collections object: Please note that my main is fluffed since I'm too lazy to create 15 employees by hand :P Code:
import java.util.ArrayList;Code:
Unsorted List: Arrays.sort(yourstack, Collections.reverseOrder()). Simple as that :) |
Quote:
Code:
Student[] students = new Student[3];Code:
class StudentComparator implements Comparator<Student> { |
Yep, IMO the comparator is the best solution.
The comparable works great if its always the same field that you plan on comparing. On the otherhand, you can do the comparator up as an abstract and extend it out to other properties; with my example you could do up an AbsEmpSorter and extend it up for EmpSorterID, EmpSorterFirstName and EmpSorterLastName. Since these are all typeof Comparator it works perfectly inside of the Arrays.sort method. Another option is to create a collection for the Employee, either by extending a collection or simply holding an array of given values. I would extend the collection, I can't recall offhand if you need to override any of the sort or reverse functions, but I still like containing everything in objects instead of arrays. Combine the collections with comparable objects for it, and you've got one awesome sortable object, with an rsort built in! |
| All times are GMT +1. The time now is 07:13 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.