0

I have a class (that implement Comparable) composed by:

double[1][2];

I would sorting my arrayList and i tried in this way but i reported an error:

public double compareTo(Matrix another) {
return this.getCell(0,1).compareTo(another.getCel(0,1));
} 

How can sorting in this way?

5
  • 1
    What error? Where? What does getCell return? Btw you wrote it wrong the second time getCel. Commented Aug 17, 2013 at 23:32
  • 2
    compareTo should return an int Commented Aug 17, 2013 at 23:33
  • Why do you have a 1x2 array of doubles? Why not double[2]? Commented Aug 17, 2013 at 23:41
  • As andy256 said, compareTo should return an int, and that could be causing the problem. But also, your getCell method should return an Integer (wrapper class) and not an int. Since you haven't posted the error, it's impossible to say. Please post your error message next time. Commented Aug 17, 2013 at 23:44
  • getCell return double. How can compare double? Commented Aug 17, 2013 at 23:46

2 Answers 2

2

Presumably, the call to getCell() returns a double, which doesn't have methods (like (compareTo()).

Also, the compareTo() method of the Compareae interface must return int, not double.

Try this:

public int compareTo(Matrix another) {
    double diff = getCell(0,1) - another.getCel(0,1);
    return diff == 0 ? 0 : diff > 0 ? 1 : -1;
}

This solution will work in all java versions. For java 7+, you may do thus instead:

public int compareTo(Matrix another) {
    return Double.compare(getCell(0, 1), another.getCell(0, 1));
} 

Also note the slight clean up of removing the redundant this. from your code.

Sign up to request clarification or add additional context in comments.

Comments

1

Your question is not very clear and it would help to post an SSCCE. But since getCell returns double, your method should probably look like this:

public int compareTo(Matrix another) {
    return Double.valueOf(this.getCell(0, 1))
            .compareTo(Double.valueOf(another.getCell(0, 1)));
} 

The way this works is to wrap each compared double primitive in a Double object. Since Double implements Comparable<Double>, your method can delegate to Double.compareTo.

Alternatively, you could use the static utility method Double.compare(double, double):

public int compareTo(Matrix another) {
    return Double.compare(this.getCell(0, 1), another.getCell(0, 1));
} 

This is preferable because it's more concise, but I wanted to mention the first solution because it involves boxing primitives to their object counterparts, which is often necessary in general in order to take advantage of class methods and to use primitives in collections.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.