hoolir
hoolir

Reputation: 21

push in priorityqueue

I want to push some int to a priorityqueue but i can't! i used the queue.add() code but this code will return the sorted queue,please help,thank you!

Upvotes: 2

Views: 3907

Answers (3)

user207421
user207421

Reputation: 310980

I want to push some int to a priorityqueue

'Push' is a stack operation, not a queue operation.

but i can't! i used the queue.add() code but this code will return the sorted queue

No it won't. A PriorityQueue is only sorted for the purposes of removing the head of the queue.

Your question doesn't make much sense. If you want to push, use a stack. If you don't want what a PriorityQueue does, don't use it.

What exactly is your actual problem?

Upvotes: 0

polygenelubricants
polygenelubricants

Reputation: 383866

A push/pop operation is clearly defined for a stack abstract data type; I'm not sure if it makes sense for a queue (or even a priority queue).

PriorityQueueimplementsQueue, which only specifies add/remove. On the other hand, a Deque has addFirst/Last, removeFirst/Last, etc. Perhaps one of these is what you're looking for.


An example

Here's an example of using a PriorityQueue of String, using a custom Comparator that compares lengths.

    Queue<String> queue = new PriorityQueue<String>(
        100, new Comparator<String>() {
            @Override public int compare(String s1, String s2) {
                return Integer.valueOf(s1.length()).compareTo(s2.length());
            }
        }
    );
    queue.add("Sally");
    queue.add("Amy");
    queue.add("Alice");

    System.out.println(queue);
    // "[Amy, Sally, Alice]"

    System.out.println(queue.remove());
    // "Amy"

    System.out.println(queue.remove());
    // "Alice"

    queue.add("Tina");
    System.out.println(queue.remove());
    // "Tina"

As expected, the PriorityQueue will give the shortest String in the queue upon remove. Also as specified, ties are broken arbitrarily.

Related questions

On PriorityQueue

On Comparator and Comparable

Upvotes: 2

cHao
cHao

Reputation: 86535

The whole point of a priority queue is that it returns the smallest entry (or rather, the first element that'd appear in a sorted list) first. If that's not what you want, you probably don't want a straight PriorityQueue.

What you could do is create a class that has a PriorityQueue for the usual stuff, and a stack for "emergencies". Have a push(T) method that adds stuff to the stack, and an add(T) that adds to the queue. Whatever method gets the next element should remove it from the stack if there's anything there, else it gets the queue's next element.

Upvotes: 0

Related Questions