I have Employee class which have age, salary, designation field.
I am adding 15 different element of Employee in Arraylist.
Sometime i want to sort collection on the basis of age, sometime designation or salary.
I tried with comparator, but for one field.
But how can i change sort parameter?
.....I always just used the standard compare method, but used a static variable that defaulted to "x".....but could be set to any other sort that I wanted to make based on whatever I set the variable to...
sloppy sudo code here
Please keep in mind that this was just a quick down and dirty example, but allows you to do the default sort option only, but just set a variable to determine the sort. I usually setup an enum for the sorting variable.
I must admit, I really don't like that approach. Apart from the problem I just mentioned (where you could actually have your sort method change in the middle of the sort algorithm if you're not careful), it's not immediately obvious which method you're using just by looking at the line doing the sorting. You've got to work out what it was last set to. Yes, that may be in the previous line, but there's a lot of potential for reuse.
It also breaks the general convention that Comparable implements the natural ordering.
In a serious application, I tend to use this approach:
Then you can just use it like this:
It might take a little more setting up, but it makes it extremely clear at the point of use.
I like that. Truth be told I used that sorting in my C# class in college simply to get done with the silly test...it worked I passed didn't use it again. Like I said there was no possibility in the application it was used in. I do like the implementation that you provided though. Doesn't look like it will take that much extra time if any then setting up and enum + the if/else/switch/whatever to determine how to do the sorting.