Cannot invoke compareTo(double) on the primitive type double(无法对原始类型 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 double
s in an array of primitives, and avoid autoboxing before calling an instance method.
这篇关于无法对原始类型 double 调用 compareTo(double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法对原始类型 double 调用 compareTo(double)


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01