Search code examples
javacompareto

primitive type double error


sorry if my question looks very stupid. I get error on .compareTo() Cannot invoke compareTo(double) on the primitive type double! how can i fix this ? Thank you!

Vehicle class:

public class Vehicle implements IOutput {
private double cost;}

public double getCost(){
        return cost;
    }

Array Class:

public static void sortByVehicleMakeModel(Vehicle[] vehicles) {

    boolean swapped = true;

    for(int y = 0; y < vehicles.length && swapped; y++) {
        swapped=false;
        for(int x = 0; x < vehicles.length - (y+1); x++) {
            if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()) > 0){
                swap(vehicles, x, x + 1);
                swapped=true;
            }
        }
    }
}

my other codes works fine:

public static void sortByOwnerName(Vehicle[] vehicles) {
    boolean swapped = true;

    for(int y = 0; y < vehicles.length && swapped; y++) {
        swapped=false;
        for(int x = 0; x < vehicles.length - (y + 1); x++) {
            if(vehicles[x].getOwner().getName().compareTo(vehicles[x + 1].getOwner().getName())> 0) {   
                swap(vehicles, x, x + 1);
                swapped=true;
            }
        }
    }
}

Solution

  • Change the return type of your getCost() method from double to Double and it will all work. Auto boxing will take care of the rest.