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!
-
Clarify what your problem with `add` is, and how `push`, if it exists, would've behaved differently. – polygenelubricants Jun 20 '10 at 10:00
-
Is this the max you can do in terms of posting real vague questions? If you can't use standard library code (whichever standard that is) try implement hands on; heap is the usual choice of data structure. – Fanatic23 Jun 20 '10 at 10:33
3 Answers
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).
PriorityQueue
implements
Queue
, 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
- Java: How do I use a PriorityQueue?
- In Java what should I use for a PriorityQueue that returns the greatest element first?
On Comparator
and Comparable

- 1
- 1

- 376,812
- 128
- 561
- 623
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?

- 305,947
- 44
- 307
- 483
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.

- 84,970
- 20
- 145
- 172