问题描述
我如何获得对我想要排序的内容进行排序?
How do I get a PriorityQueue
to sort on what I want it to sort on?
此外,和方法?
Also, is there a difference between the offer
and add
methods?
推荐答案
使用构造函数重载需要一个比较器<?超级E>比较器
并传入一个比较器,以适当的方式比较您的排序顺序。如果你举一个如何排序的例子,我们可以提供一些示例代码来实现比较器,如果你不确定的话。 (虽然这很简单。)
Use the constructor overload which takes a Comparator<? super E> comparator
and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)
正如其他地方所说: offer
和 add
只是不同的接口方法实现。在我已经获得的JDK源代码中,添加
调用 offer
。虽然添加
和商品
但潜在通常具有不同的行为,因为 offer
表示由于大小限制而无法添加该值,这种差异与 PriorityQueue
无关是无关紧要的。
As has been said elsewhere: offer
and add
are just different interface method implementations. In the JDK source I've got, add
calls offer
. Although add
and offer
have potentially different behaviour in general due to the ability for offer
to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue
which is unbounded.
以下是按字符串长度排序的优先级队列示例:
Here's an example of a priority queue sorting by string length:
// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test
{
public static void main(String[] args)
{
Comparator<String> comparator = new StringLengthComparator();
PriorityQueue<String> queue =
new PriorityQueue<String>(10, comparator);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0)
{
System.out.println(queue.remove());
}
}
}
// StringLengthComparator.java
import java.util.Comparator;
public class StringLengthComparator implements Comparator<String>
{
@Override
public int compare(String x, String y)
{
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() - y.length(),
// which would be more efficient.
if (x.length() < y.length())
{
return -1;
}
if (x.length() > y.length())
{
return 1;
}
return 0;
}
}
这是输出:
medium
很长确实
这篇关于我如何使用PriorityQueue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!