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

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

问题描述

return array [index1] .compareTo(array [index2]); 提供一个错误无法对原始类型调用compareTo 。如何解决这个问题?

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 与调用 static 比较方法,如下所示:

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天全站免登陆