2

I am new to java. I have not understood one thing while implementing the following code:

public class Demo 
{
class DemoComparator implements Comparator<Board>
{
    @Override
    public int compare(Board A, Board B) { 
        return A.f()-B.f();
    }
PriorityQueue<Board>Q = new PriorityQueue<>(10, new DemoComparator());

}

Here, Board is a class which I haven't shown and f() is a function that returns an integer value. My question is if I write:

Q.add(element1);
Q.add(element2);
Q.add(element3);

where, element1,element2 and element3 are of type Board and have their own f values returned from their respective f() function.

Will element1,element2 and element3 be stored in the priority queue according to their f values considering any increasing or decreasing order? and when the line: return A.f()-B.f(); will be called?

1
  • why don't you consider Comparable<T> instead of Comparator<T>? Commented Apr 5, 2016 at 18:14

2 Answers 2

4

Yes, the elements will be ordered by the Comparator you pass the constructor. From the docs:

https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

The head of the queue is the item with the lowest value. The comparator will be called on the constructor or when you call add() from the collection interface or the offer() method from the queue interface. Just look at the source code:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/PriorityQueue.java#267

Or write a little test that proves it's happening.

Sign up to request clarification or add additional context in comments.

1 Comment

will the comparator be called when I call add() from the second time and later? @Robert Moskal
1

If the f values are themselves Comparable you may want to use

return A.f().compareTo(B.f());

This would ensure that your data is sorted by the natural ordering of f, otherwise you can simply define the Comparator functionality yourself as you did in the provided example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.