java 中的 compareTo 方法 return 是什么

What does compareTo method return in java

我有一个代码片段,它在一个数组中找到中位数,然后根据与中位数的接近程度(从最小到最大)对该数组进行排序,但我不明白这些东西是如何工作的

 public static Integer[] sort(Integer[] array)
    {
        Arrays.sort(array);
        final double median;
        if (array.length % 2 == 0)
            median = ((double)array[array.length/2-1]+ (double)array[array.length/2])/2;
        else
            median =  array [array.length/2];

        Comparator<Integer> compareToMedian= new Comparator<Integer>()
        {
            @Override
            public int compare(Integer o1, Integer o2)
            {
                double value = Math.abs(o1 - median) - Math.abs(o2 - median);
                if (value == 0)
                    value = o1 - o2;
                return (int)value;
            }
        };

        Arrays.sort(array, compareToMedian);
        return array;
    }

我真正感到困惑的是在这种特殊情况下价值的确切含义。它只是从最小到最大对结果进行排序吗?就像我在一种情况下 result 等于 -5,在另一种情况下等于 -2 和 3,最终它变成 -5、-2、3?并对数组进行排序?

compareTo() return 显示哪个值更大的整数

0 如果两者相等

+ve 如果第一个值更大

-ve 如果第二个值更大


compareTo(5,5) returns 0

compareTo(6,5) returns 任何正数

compareTo(5,6) return任何负值

//    going line by line for explanation

    public static Integer[] sort(Integer[] array)
    {
        Arrays.sort(array);//first of all sort the numbers in increasing order
        final double median;
        /*
        now in sorted numbers median is the
        --- average of middle two values for even count of numbers; like for 10 numbers median is (4th item +5th item )/2
        --- middle value if there are odd count of numbers like for 11 items the median is the 6th item
         */
        if (array.length % 2 == 0)
            median = ((double)array[array.length/2-1]+ (double)array[array.length/2])/2;
        else
            median =  array [array.length/2];
        //now we have the median



//        here we have a Comparator for comparing any value during with the median value
        Comparator<Integer> compareToMedian= new Comparator<Integer>()
        {
            @Override
            public int compare(Integer o1, Integer o2)
            {
//                first we check the distance of two numbers from the median; that is the difference from the median
                double value = Math.abs(o1 - median) - Math.abs(o2 - median);
                if (value == 0)//if the difference is same then we compare the numbers
                    value = o1 - o2;
                return (int)value;//otherwise we return the difference
            }
        };

        Arrays.sort(array, compareToMedian);//sort the numbers with respect to median
        return array;
    }