aspose file tools*
The moose likes Java in General and the fly likes Sorting with Collator and Collections ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting with Collator and Collections ??" Watch "Sorting with Collator and Collections ??" New topic
Author

Sorting with Collator and Collections ??

Frank Jacobsen
Ranch Hand

Joined: May 17, 2002
Posts: 353
Can someone put in the missing link...

I have a list off object, i want to sort after the secound field in the object...

Loke at this code:



Frank
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Have you tried implementing Comparator instead of Comparable? Your code looks more like a Comparator because it has the two-argument compare and nothing in the one-argument compare. You can pass a Comparator to the constructor of a sorted collection like TreeSet and then just add your objects one at a time or addAll with the list you have here.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Notice the compareTo() "stub" that takes only one argument. If you are using the Comparable interface, you need to fill in this method with code similar to what you have written. As Stan said, you need to implement Comparator instead in order to use the compareTo() method with two parameters. Also note that you will need to pass the Comparator to the Collections constructor in order to sort it properly.

Layne


Java API Documentation
The Java Tutorial
Geoffrey Falk
Ranch Hand

Joined: Aug 17, 2001
Posts: 171
    
    1
Very simple.. impose a natural order on Kunde by implementing the Comparable interface. Then the Collections.sort() method will work very easily.



Or if you didn't want to change Kunde to make it Comparable, you could do this:



Geoffrey
[ May 11, 2005: Message edited by: Geoffrey Falk ]

Sun Certified Programmer for the Java 2 Platform
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting with Collator and Collections ??