question about how to program this...

here is my situation..

i have a class I wrote. I need to be able to sort it easily on 3 different data

elements it holds. Meaning = sometimes i need a list of it sorted on data

element 1, sometimes on 2, but not always 3. Hence, i would like to be able

to put a switch statement in the equals function. However, since the equals

function has no way of receiving such a parameter, I need to figure out the

best way to do this.

The proposed solution: i have thought (and tried) just adding a static integer

that each class can look at to tell what type of sort to do. Problem: the problem i

have with this solution is that i use this class in lots of different places. it seems

like it would be bad programming practice to have a static data element that

was only true for the data elements I am sorting, but not true for the other ones.

My reasoning is that i can change the value of this element before any sort

is brought to pass. However, that seems a bit weird to me. Am I overreacting?

Is this, indeed, bad programming practice? Is there some solution available

to me that i've overlooked? any answers/suggestions/comments are greatly

appreciated.

[1261 byte] By [pnandrusa] at [2007-11-26 21:38:35]
# 1

I see 2 options.

1) have 3 seperate sorts based on each possible one (if they are not similar)

2) have one sort with a parameter that states which of the 3 sorts to use. Make the 3 possible values static final values so they can not change, and you only need one copy of them around.

Aknibbsa at 2007-7-10 3:21:42 > top of Java-index,Java Essentials,Java Programming...
# 2
Implement 3 different Comparators, one for each sorting method. Then pass a parameter to your sorting method that indicates which way to sort. Apply the appropriate Comparator when sorting. http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html
hunter9000a at 2007-7-10 3:21:43 > top of Java-index,Java Essentials,Java Programming...
# 3
Create three Comparators.[url= http://www.onjava.com/lpt/a/3286]Making Java Objects Comparable[/url] http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html
jverda at 2007-7-10 3:21:43 > top of Java-index,Java Essentials,Java Programming...