Link to home
Start Free TrialLog in
Avatar of inzaghi
inzaghi

asked on

how to sort objects ascending and descending

How would you use comparators to sort objects ascending and descending.

Suppose I want to be able to sort an object by the age field either ascending or descending.
Also I have an object that can be sorted by more than field. You can sort by name and age.
How can I implement more than 1 comparator?

SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland 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
ASKER CERTIFIED SOLUTION
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
Typo:

>>Reverse the comparison for asc.ssec

should have been

Reverse the comparison for asc/desc
Avatar of inzaghi
inzaghi

ASKER

I am using java 1.4
:-)

You only need one Comparator
Avatar of inzaghi

ASKER

Alternatively I could have one class which implements the Comparable interface and otehr comparators I can define as annonymous classes

 public static final Comparator AGE_ORDER = new Comparator() {
             public int compare(Object o1, Object o2) {
             }
 };

 public static final Comparator NAME_ORDER = new Comparator() {
             public int compare(Object o1, Object o2) {
             }
};
> Alternatively I could have one class which implements the Comparable interface and otehr comparators I can define as annonymous classes

yes you could use inner classes for your comparators. It would still give you a seperate class for each sort order you needed, ie. one comparator per sort order.