jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Help needed on use of the Comparable interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help needed on use of the Comparable interface" Watch "Help needed on use of the Comparable interface" New topic
Author

Help needed on use of the Comparable interface

Melinda Savoy
Ranch Hand

Joined: Jun 21, 2005
Posts: 387

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
Sheriff

Joined: Sep 28, 2004
Posts: 19060
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help needed on use of the Comparable interface