wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Collections.sort(list, comparator) doesnt work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections.sort(list, comparator) doesnt work" Watch "Collections.sort(list, comparator) doesnt work" New topic
Author

Collections.sort(list, comparator) doesnt work

Paul McKenna
Ugly Redneck
Ranch Hand

Joined: Jul 08, 2000
Posts: 1006
Hi..
I have created a Comparator and I have a list. When I use the static method in Collections, called sort.. the sort works sometimes but on other occasions does not.
That is it sorts as though 108 < 12 is true
Can anyone explain why?
Thanks
SR


Commentary From the Sidelines of history
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

post your comparator code. Just from looking at your current results, it looks like it is comparing objects lexicographically ( like comparing Strings ) rather than as a number value.
Jamie
[ August 29, 2002: Message edited by: Jamie Robertson ]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
My guess is that your comparator needs work. Post the code and we'll take a look.
You might want to take a look at this thread:
http://www.coderanch.com/t/355091/Servlets/java/order-DB-results-servlets


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Paul McKenna
Ugly Redneck
Ranch Hand

Joined: Jul 08, 2000
Posts: 1006
Hi..
Thanks a lot to both of you. I did find the mistake. You see the Comparator was working fine, but like Jamie pointed out, the List had string objects in it. And in String comparisons, 108 < 12 is true.
I rectified that by changing such objects to integer and it worked fine.
Thanks a lot again.
SR
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Timeout.
You can't compare objects with < - it's for comparing primitive numerical types only.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Originally posted by Dirk Schreckmann:
Timeout.
You can't compare objects with < - it's for comparing primitive numerical types only.

I don't think he was doing a < directly. He was probably using the string compare method which does a < == > compare.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections.sort(list, comparator) doesnt work