question: if i have a collection of objects, which are all the same, and the class has at least 3 different attributes. i want to sort this collection from time to time in respect to one of the attributes. the next time i sort it i want to do it in respect to a different attribute. whats the best way and most effecient way to do this?
I would create an internal variable in the class definition which can be used in the compareTo method when you implement Comparable. You can then change that variable before you sort.
... or better, simply implement three different "Comparator" objects, and use those for sorting. All Java's "sort" methods accept an optional Compartor object to do the comparisons. This is likely to be simpler and less error-prone.
What you showed was an anonymous inner class implementation of a Comparator. That works really well in some cases, and might be what you need. But, if you will be using the same type of sort in more than one place in your code, you would likely have this code in more than one place.
Just in case this was the only way you've seen Comparator implemented, realize it can be done in the "old fashioned" way as well:
and similarly for KeyTwo and KeyThree. Another thing I've seen done that I like is defining the different Comparators as final static members of the class they are used to sort: