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?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With