Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting with Collator and Collections ??

 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Geoffrey Falk
Ranch Hand
Posts: 171
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic