dev
dev

Reputation: 11319

IllegalArgumentException : Comparison method violates it's general contract

Following is my Comparator :

class CostComparator implements Comparator<Index> {
    @Override
    public int compare(Index itemIndex1, Index itemIndex2) {
    return Grid[itemIndex1.x][itemIndex1.y].cost >
        Grid[itemIndex2.x][itemIndex2.y].cost ? 1 : -1;
    }
}

The Grid above is a 2D array of item indexes. I have some memory considerations because of which I am storing indices instead of items in the Grid.

The compare method takes the indices and compares the cost of the Items at those indices.

Upvotes: 0

Views: 62

Answers (2)

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

You are missing the case where both values are equals

return Grid[itemIndex1.x][itemIndex1.y].cost >
        Grid[itemIndex2.x][itemIndex2.y].cost ? 1 : -1;

Should be changed to

return Integer.compare(Grid[itemIndex1.x][itemIndex1.y].cost,
    Grid[itemIndex2.x][itemIndex2.y].cost);

See documentation for more information on how to implement.

Also, you might want to check for possible null values before doing the comparison.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502016

Simply put, it violates the comparison if two indexes have the same cost. It should return 0, but it will return -1. As a trivial violation, that means that compare(index, index) will always return -1, when it must return 0.

It's really easy to fix though:

return Integer.compare(Grid[itemIndex1.x][itemIndex1.y].cost,
    Grid[itemIndex2.x][itemIndex2.y].cost);

(Change Integer to whatever the type of cost is.)

Upvotes: 4

Related Questions