• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting

 
Andy Lucz
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21015
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21015
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic