1

I am using the following compareTo-Method (in this case for two strings)

Collections.sort(stringList, new Comparator<String>() {
            public int compare(String a, String b) {
                return a.compareTo(b);
            }
        });

in my current Android-Project. The compareTo-Function sets special characters like #'. and numbers before letters. Can I modify compareTo somehow, that letters are before numbers and numbers before special characters simple as possible? Or do I need to write the compare-method by my own?

Thanks in advance!

Dominik Seemayr
  • 830
  • 2
  • 12
  • 30
  • try making a custom method by modifying the original source code: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/String.java#String.compareTo%28java.lang.String%29 – MCMastery Jun 24 '15 at 19:18
  • To deviate from strings being compared by their characters' ASCII values, you will need to loop through the characters of the strings yourself and apply your custom logic there in the `Comparator`'s `compare` method. – Dan Harms Jun 24 '15 at 19:18

1 Answers1

1

You cannot override compareTo() method of String, but you can definitely provide your own Comparator with a custom compare() method in relevant places such as Collections.sort(). Remember that String compareTo() does a lexicographic comparison. More information in Java String class documentation.

Is your need just about reversing the compareTo() output? Then a compare() method as simple as the following could work (notice the Java unary - operator):

        public int compare(String a, String b) {
            return (- a.compareTo(b));
        }
Joy Patra
  • 722
  • 7
  • 9