File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes many comparator classes? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "many comparator classes?" Watch "many comparator classes?" New topic

many comparator classes?

H Melua
Ranch Hand

Joined: Jan 04, 2005
Posts: 172

i wrote a program that has alot of sorting methods, is there a way of going it without having too many comparator classes??

thank u
[ January 23, 2005: Message edited by: H Melua ]
M Beck
Ranch Hand

Joined: Jan 14, 2005
Posts: 323
i don't know - why would you use more than one or two per datatype?

most sorting algorithms use a comparison operation to determine which of two things should be sorted before the other. usually, if you're writing your own comparison code, it's either because (1) you want to sort things in some unusual and tricky order, such that the simple built-in "<" / ">" operators won't do the job; or (2) because the things you want to compare are complex, derived data types that those built-in operators just don't work on.

it seems to me that, either way, you would usually need no more than two comparators for each type of thing; one to compare "is less than" and the other for "is greater than". then you should be able to decide whether to sort in ascending or descending order by simply passing one or the other of those to your sorting algorithm. am i right, or am i confused?

two comparators per datatype doesn't seem like a whole lot to me, i guess is what i'm saying. how many have you got?
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
I usually implement Comparable rather than providing a Comparator, but I must admit most of the sorting I need to do is rather simplistic

H Melua
Ranch Hand

Joined: Jan 04, 2005
Posts: 172

well true, but i just wanted to know for the sake of efficiency thats all.
I have implemented comparable and also comparators, since i need 4 sorting orders, and i do think 3 is alot :roll: for comparator!!! and even if it wasnt that much, im still wondering if there is a better way...

thanks for replying
[ January 23, 2005: Message edited by: H Melua ]
I agree. Here's the link:
subject: many comparator classes?
Similar Threads
Comparable vs Comparator
Sorting the String Saved in ArrayList
Comparator interface
Comparable & Comparator
object sorting in a Vector