Reputation: 11319
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
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
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