GeeCON Prague 2014*
The moose likes Java in General and the fly likes sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "sorting" Watch "sorting" New topic
Author

sorting

fred garvin
Greenhorn

Joined: Jul 19, 2005
Posts: 5
hello troops

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?

thanks
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

... 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.


[Jess in Action][AskingGoodQuestions]
fred garvin
Greenhorn

Joined: Jul 19, 2005
Posts: 5
Thank you ernest. now it occurs to me that I may have done this before. would this be what you mean(or something similar):

Collections.sort(list, new Comparator(){
public int compare(Object obj1, Object obj2) {
String string1 = (String)obj1;
String string2 = (String)obj2;

return string2.length() - string1.length();
}
});
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Yep, exactly.
Jon Egan
Ranch Hand

Joined: Mar 24, 2004
Posts: 83
Fred,

One more thought on this:

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:




Then, you can call the sort like this:



Hope this helps,
-- Jon
fred garvin
Greenhorn

Joined: Jul 19, 2005
Posts: 5
very elegant Jon, I will indeed steal your code and use it. Thank you.
[ February 18, 2006: Message edited by: fred garvin ]
 
GeeCON Prague 2014
 
subject: sorting