views:

13

answers:

1

The Priority Queue implementation in the Java standard library appears to be a min Priority Queue which I found somewhat confusing. In order to turn it into a max one I created a custom comparator object.

Comparator<Integer> cmp = new Comparator<Integer>()
{
    public int compare( Integer x, Integer y )
    {
        return y - x;
    }
};

I was wondering if there was a more elegant solution. Essentially I wan't a generic priority queue that could be used to implement Dijkstras etc. I didn't even realise there would be ones which operated in reverse :/

A: 

If you have an existing comparator you could create a generic inversing comparator.

public class InverseComparator<T> implements Comparator<T> {
    private final Comparator<T> delegate;

    public InverseComparator(Comparator<T> delegate) {
        this.delegate = delegate;
    }

    public int compare(T x, T y) {
        return delegate(y, x);
    }
}
Michael Barker