Please could someone suggest the best possible solution to the following problem (this is part of a program I am trying to code) :
I have a class Foo with member variables and another class Bar which extends Foo. Bar adds extra member variables. Bar objects are stored in a collection and as such I would like to order these objects by any of their member variables.
I considered using an enum type containing the member variables for the classes that could be passed as an argument to the compareTo() method but as enumerated types are implicitly static I cannot add parameters for the member variables for Bar or any other classes that may extend Foo that I want to compare. For example, I want to compare two Bar classes by the member variable 'myVar' I would call something like bar1.compareTo(bar2, MyEnum.MYVAR) and the classes would be compared against their myVar values. I am thinking that I may just have to create seperate methods to order by each member variable but want to use compareTo() as it is used by Java collections to automatically sort its items (I believe).
That is as clearly as I can describe the problem but I am probably going about achieving this the completely wrong way. Any pointers would be greatly appreciated.
EDIT - This is similar behaviour to sorting columns in a Windows Explorer window by different attributes i.e. Date Modified, File Name, size, etc.
You're better off using a Comparator instead to encapsulate this particular comparation logic. You can do as many Comparator
object as possible comparations you want to make or, as suggested, have the Comparator
to compare based on a determined field.
It's up to you if you want to have multiple comparators or just one, but if you want to make complex comparations based on multiple fields I suggest you create a particular comparator for that.