无法对原始类型 double 调用 compareTo(double)

2022-01-25 00:00:00 compare java comparable compareto

return array[index1].compareTo(array[index2]); 行提供了一个错误无法在基本类型 double 上调用 compareTo(double)".如何解决这个问题?

The line return array[index1].compareTo(array[index2]); provides an error "Cannot invoke compareTo(double) on the primitive type double". How to solve this issue?

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*::  This function implements a comparator of double values        :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private class ArrayIndexComparator implements Comparator<Integer>
{
    private final double[] array;

    public ArrayIndexComparator(double[] array)
    {
        this.array = array;
    }

    public Integer[] createIndexArray()
    {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++)
        {
            indexes[i] = i; // Autoboxing
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2)
    {
         // Autounbox from Integer to int to use as array indexes
        return array[index1].compareTo(array[index2]);
    }
}


double[] dist = new double[centroids.size()];
// fill array...    
ArrayIndexComparator comparator = new ArrayIndexComparator(dist);
Integer[] indexes = comparator.createIndexArray();
Arrays.sort(indexes, comparator);

推荐答案

将实例方法compareTo的调用替换为静态compare方法,像这样:

Replace the call of an instance method compareTo with the call of static compare method, like this:

return Double.compare(array[index1], array[index2]);

这使您可以将 double 保存在原始数组中,并避免在调用实例方法之前进行自动装箱.

This lets you keep your doubles in an array of primitives, and avoid autoboxing before calling an instance method.

相关文章