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

Help needed on use of the Comparable interface

 
Melinda Savoy
Ranch Hand
Posts: 387
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had posted a question last Friday regarding the use of Comparator and for my situation I learned that the Comparable interface was a better fit. However, I have another question and hoped that this group could help.

My understanding is that the COMPARETO method in the Comparable interface sorts based on the ASCII table order. Meaning that the numeric values would sort before the alpha values. My problem is that the list that we need to display on an intranet application needs to be sorted by ALPHA values first then by NUMERIC values. How can I accomplish this using the compareTo method? Here is the code that I have when I use the compareTo method that sorts almost like what I'm needing but falls a little short:



The results that I'm getting from the code above is as follows:

BinSortCode: Description:
C2 Desc1
B99999 Desc2
A Desc3
999999 Desc4
799999 Desc5
1 Desc6
0A3 Desc7
0234D Desc8
00009 Desc9

I need the results to be displayed as:
BinSortCode: Description:
A Desc3
B999999 Desc2
C2 Desc1
00009 Desc9
0234D Desc8
0A3 Desc7
1 Desc6
799999 Desc5
999999 Desc4

Any help or direction to get to the results that I need to be displayed would be greatly appreciated. Thanks.


[HENRY: Added Code Tags]
 
Henry Wong
author
Marshal
Pie
Posts: 20889
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding is that the COMPARETO method in the Comparable interface sorts based on the ASCII table order.


The comparable for String, uses the ASCII value because that is how it is done. If you want it to do something else, then don't call the strings compare to method blindly. Add extra checks to see if the components are digits or characters -- if they are both the same type, then use the string comparator, if they are not, then return the answer. (it's a bit more complicated than that, but you should get the picture)

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic