Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why these two code snippets yield the same result?

I was looking at a bunch of code which was like this and used Comparator<T> to sort an array of Strings ( The only reason I'm asking this question is that I'm curious about how Comparator<T> handles all this ):

 String[] names = //An string array

 Arrays.sort(names, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return (o1.length()-o2.length());
        }
    });

I am familiar with this :

Arrays.sort(names, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if(o1.length()>o2.length())
                return 1;
            else if(o1.length()==o2.length())
                return 0;
            else
                return -1;
        }
    });

Which handles if the length the first String is bigger return 1 and return -1 if the second one is bigger and zero if they are of the same length. But the first snippet returns the difference between their length which could be less than -1 and more than 1. So how do Comparator<T> handle all this that they yield the same result?


1 Answers

From https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare(T,%20T):

Returns: a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

It doesn't need to be -1 or 1, but simply a negative integer or a positive integer.

like image 157
sp00m Avatar answered Mar 15 '26 09:03

sp00m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!