Softey
Softey

Reputation: 1491

Java CompareTO with double Values

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?

Upvotes: 5

Views: 26430

Answers (6)

Nagaraja G Devadiga
Nagaraja G Devadiga

Reputation: 397

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);
}

Upvotes: 7

Aditya
Aditya

Reputation: 1344

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.

Upvotes: 14

Boris
Boris

Reputation: 24443

You should implement a Comparator interface:

class OFSComparator implements Comparator<Member> {
   public int compare(Member m1, Member m2) {
      return (m1.ofs.compareTo(m2.ofs));
   }
}

Each Member should have a field for overall fitness score

Double ofs;

And if you later want to sort members based on their overall fitness score, you can use Arrays.sort:

Arrays.sort(members, new OFSComparator());

Upvotes: 0

Arjit
Arjit

Reputation: 3456

You can try this.

Double obj1 = this.overall;
Double obj2 = o.overall;

int retval =  obj1.compareTo(obj2);

//then do your normal if else block.

Upvotes: 0

Mauren
Mauren

Reputation: 1975

Your compareTo() method receives a FitnessScore object. However, it does not test for null case.

When o is null, your method will throw a NullPointerException.

Upvotes: 0

GreenOnBlack
GreenOnBlack

Reputation: 66

You need to implement the Comparator interface. Dont worry about your values. Even if the compare method is returning an int. This int is not one of your values.

Also check this out. Comparator with double type

Upvotes: 1

Related Questions