views:

65

answers:

4

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!

+1  A: 

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

polygenelubricants
A: 

Please show us what you have got so far.

As you can read here, PriorityQueue will always return true: Queue

InsertNickHere
i'm very beginner,i confused,i can't find addFirst in this page.
hoolir
@hoolir You have mentioned "queue.add()" in your question, and this is what the page shows you.
InsertNickHere
A: 

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?

EJP
A: 

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.

cHao