aspose file tools*
The moose likes Beginning Java and the fly likes Sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting" Watch "Sorting" New topic
Author

Sorting

Andy Lucz
Greenhorn

Joined: Aug 31, 2008
Posts: 2
I have a quesion about sorting in java. When I sort a table of strings like this:

String a [] = {"a","_A","_a","b","A","aA","bA"};
Arrays.sort(a);

As a result I have a table with this order: A, _A, _a, a, aA, b, bA. I think it's incorrect because for example _A should be before A. Why Java does not interpratate _ sign correctly ? How to solve this problem? When I sort such table in Excel as a result I got _A, _a, A, a, aA, b bA which I think is correct order.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18996
    
  40

The sort() method that you are using, uses the natural order to sort the strings (as defined in the JavaDoc). If you look at an ASCII table, you will notice that the underscore is after the capital letters. So, it is correct. Or at the very least, it is what the JavaDoc says it should be.

Now, if you don't want the natural (ASCII) order, then you will have to use the overloaded sort() method that takes a comparator. Just write a comparator that defines the underscore as before the capital letters, and use it in the sort() method.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39868
    
  28
Go to the Unicode pages and you find that _ comes after A and before a so you are sorting correctly. There is a case-insensitive Comparator which I think is a static field of the String class, which might sort out your problem.
Andy Lucz
Greenhorn

Joined: Aug 31, 2008
Posts: 2
Just write a comparator that defines the underscore as before the capital letters, and use it in the sort() method.


Unfortunatly I'm new to java and I don't know how to write such comparator . Could you give me some tips, how to to this? Please.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18996
    
  40

A comparator is merely an object that implements the Comparator interface. This interface takes only one method, the compare() method, and it is incredibly straigntforward. In fact, for someone "new to Java", writing a comparator may be a good and short learning exercise.

Here is the JavaDoc of the interface to get you started...

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting