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?

inzaghiAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
objectsConnect With a Mentor Commented:
You would use a different Comparator for each sort order that you needed.
To get the reverse order iuse:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder(java.util.Comparator)
0
 
CEHJConnect With a Mentor Commented:
You can pass the field as a parameter to the ctor of the Comparator. Reverse the comparison for asc.ssec
0
 
CEHJCommented:
Typo:

>>Reverse the comparison for asc.ssec

should have been

Reverse the comparison for asc/desc
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
inzaghiAuthor Commented:
I am using java 1.4
0
 
CEHJCommented:
:-)

You only need one Comparator
0
 
inzaghiAuthor Commented:
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) {
             }
};
0
 
objectsCommented:
> 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.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.