无法对原始类型 double 调用 compareTo(double) [英] Cannot invoke compareTo(double) on the primitive type double

查看:60
本文介绍了无法对原始类型 double 调用 compareTo(double)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于无法对原始类型 double 调用 compareTo(double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆