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.
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.)
See more on this question at Stackoverflow