Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java CompareTO with double Values

Tags:

java

I need to be able to rearrange a group of people from their overall fitness score. I am able to do a compareTO method with ints but as soon as its with doubles I get errors flying up everywhere.

public double compareTo(FitnessScore o){
    return (this.overall-o.overall);
}

It needs to be a double because there are scores like:

68.5 68.4 60.1 60.3

So casting them to an int would make it redundant. When I did have it as an int to see if it would work. I tried the following. (subjects being the array that I initialized to hold all the different instances of people)

Arrays.sort(subjects);

I get the following error:

java.lang.NullPointerExceptione

Any suggestions?

like image 424
Softey Avatar asked Mar 14 '14 12:03

Softey


2 Answers

Your compareTo must alaways return an int value.

-1 for placing it before in Collection
0 indicates same value already exists in Collection
+1 for placing it afterwards in Collection

If overall is of type Double, use this:

public int compareTo(FitnessScore o){
    return this.overall.compareTo(o.overall));
}

If overall is of type double, use this:

public int compareTo(FitnessScore o){
    if(this.overall<o.overall)
          return -1;
    else if(o.overall<this.overall)
          return 1;
    return 0;
}

And for your NullPointerException, check that your subjects is not null.

like image 87
Aditya Avatar answered Sep 21 '22 00:09

Aditya


You are breaking the signature of compareTo method. It should look like below,

public int compareTo(FitnessScore o){
    return Double.compare(this.overall-o.overall);
}
like image 22
Nagaraja G Devadiga Avatar answered Sep 20 '22 00:09

Nagaraja G Devadiga