首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在基本类型double上调用compareTo(double)

问无法在基本类型double上调用compareTo(double)
EN

Stack Overflow用户
提问于 2013-11-22 10:09:38
回答 4查看 36.4K关注 0票数 11

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

代码语言:javascript
复制
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*::  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);
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-11-22 10:13:33

将实例方法compareTo的调用替换为 method调用,如下所示:

代码语言:javascript
复制
return Double.compare(array[index1], array[index2]);

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

票数 24
EN

Stack Overflow用户

发布于 2013-11-22 10:11:46

在java中,基元类型没有任何方法。相反,使用原始数据类型使用包装类。

变化

代码语言:javascript
复制
return array[index1].compareTo(array[index2]);

至

代码语言:javascript
复制
return  new Double(array[index1]).compareTo(array[index2]);

或

尝试使用Double[] array;而不是double[] array;

票数 1
EN

Stack Overflow用户

发布于 2013-11-22 10:14:09

对于不使用compareTo的基元类型,请改用==。

但是如果您想使用compareTo,只需创建一个双数组

代码语言:javascript
复制
Double[] dist = new Double[centroids.size()];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20142192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档