Modify compareTo in Android

357 views Asked by At

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!

1

There are 1 answers

0
Patr On BEST ANSWER

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));
        }