push in priorityqueue
I want to push some int to a priorityqueu开发者_开发知识库e but i can't! i used the queue.add() code but this code will return the sorted queue,please help,thank you!
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
- When to use Comparable vs Comparator
- Java: What is the difference between implementing Comparable and Comparator?
- difference between compare() and compareTo()
- Comparable and Comparator contract with regards to null
- Why does the Java Collections Framework offer two different ways to sort?
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.
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?
精彩评论