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

Collections.sort(list, comparator) doesnt work

 
Paul McKenna
Ugly Redneck
Ranch Hand
Posts: 1006
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Paul McKenna
Ugly Redneck
Ranch Hand
Posts: 1006
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Timeout.
You can't compare objects with < - it's for comparing primitive numerical types only.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic