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 doubles in an array of primitives, and avoid autoboxing before calling an instance method.
这篇关于无法对原始类型 double 调用 compareTo(double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法对原始类型 double 调用 compareTo(double)
				
        
 
            
        基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 从 python 访问 JVM 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				