Case sensitive
java.util.Arrays.sort(myArray);
Case insensitive
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
Sort with international characters.
Take the following example :
import java.util.*;
import java.io.*;
public class TestSort1 {
String [] words = { "Réal", "Real", "Raoul", "Rico" };
public static void main(String args[]) {
new TestSort1().doit();
}
public void doit() {
try {
// to be able output french character at the console
Writer w =
new BufferedWriter
(new OutputStreamWriter(System.out, "Cp850"));
//
w.write("Before :\n");
for(int i=0; i < 4 ; i++) {
w.write(words[i] + " ");
}
java.util.Arrays.sort(words);
w.write("\nAfter :\n");
for(int i=0; i < 4 ; i++) {
w.write(words[i] + " ");
}
w.write("\n");
w.flush();
w.close();
}
catch(Exception e){}
}
}Before : Réal Real Raoul Rico After : Raoul Real Rico RéaAl
java.util.arrays.sort(words);
java.util.arrays.sort(words, java.text.collator.getInstance(Locale.FRENCH));
Before : Réal Real Raoul Rico After : Raoul Real Réal Rico
...
Locale loc = Locale.FRENCH;
sortArray(Collator.getInstance(loc), words);
...
public static void sortArray(Collator collator, String[] strArray) {
String tmp;
if (strArray.length == 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if( collator.compare(strArray[i], strArray[j] ) > 0 ) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
Written and compiled by Réal Gagnon ©1998-2005
[ home ]