user2520969
user2520969

Reputation: 1389

Sorting ArrayList in Java

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?

Upvotes: 0

Views: 146

Answers (2)

Bohemian
Bohemian

Reputation: 424953

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.

Upvotes: 2

Paul Bellora
Paul Bellora

Reputation: 55213

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.

Upvotes: 1

Related Questions