Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot invoke compareTo(double) on the primitive type 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);
like image 564
Klausos Klausos Avatar asked Nov 22 '13 10:11

Klausos Klausos


2 Answers

Replace the call of an instance method compareTo with the call of static compare method, like this:

return Double.compare(array[index1], array[index2]);

This lets you keep your doubles in an array of primitives, and avoid autoboxing before calling an instance method.

like image 85
Sergey Kalinichenko Avatar answered Nov 16 '22 10:11

Sergey Kalinichenko


In java primitive types don't have any methods. Instead using primitive data types use Wrapper classes.

change

return array[index1].compareTo(array[index2]);

to

return  new Double(array[index1]).compareTo(array[index2]);

or

try with Double[] array; instead of double[] array;

like image 1
Prabhakaran Ramaswamy Avatar answered Nov 16 '22 11:11

Prabhakaran Ramaswamy