View Single Post
Old 07-14-2004, 07:47 PM   #3 (permalink)
technobard
Centurion Nova Prime
 
technobard's Avatar
 
Join Date: May 2002
Location: Oak Park, IL (USA)
Posts: 287
technobard is on a distinguished road
I think Belisarius and I have been on opposite sides of this discussion before...or maybe it was someone else. I like the Comparable interface better than comparators. (see Sorting Objects Tutorial)

The problem is that whatever you do, you will have to define how to do the sort on a particular object variable beforehand. Being able to pick "any" string parameter is tough.

In my tutorial, I call a method called strangeFactor(). One approach would be to use a static variable to indicate which object variable to sort by and then have your code branch on that value. If you stick that code in a method like strangeFactor(), you can keep the actual compare simple.

If you're feeling really adventurous, I suspect you can make the solution more generic by using the reflection api to get the field/variable names and values for a given object. You'll still want to use a static class variable to set the sort field name. If the datatypes are something other than String, you'll also have to look at the datatype of the sort field and have code to handle the differences in comparisons, if any.

Belisarius will probably point out that if you use reflection to go this generic, a comparator is an excellent choice. Oh, well.
technobard is offline   Reply With Quote