[英]Java PriorityQueue comparator
Say that I have an shoeCollection
class that has both the shoe size and the shoe brand.假设我有一个shoeCollection
鞋码和鞋品牌的shoeCollection
类。 how do I modify the comparator such that it will sort the priorityQueue
based on shoe size?如何修改比较器,使其根据鞋码对priorityQueue
排序?
I know that priority queues already have a build-in comparator, but since my object is not an Integer or Double, I figured I need to write my own.我知道优先级队列已经有一个内置的比较器,但由于我的对象不是整数或双精度数,我想我需要自己编写。
This is my comparator right now这是我现在的比较器
static class ShoeComparator implements Comparator<shoes>
{
@Override
public int compare(shoes x, shoes y)
{
if(x.getID() > y.getID()){
return 1;
}
if(x.getID() < y.getID()){
return -1;
}
return 0;
}
}
I then declare a new Shoe priority queue with the following然后我声明一个新的 Shoe 优先队列,如下所示
private static Comparator<shoes> comparator = new shoeComparator();
private static PriorityQueue<shoes> list = new PriorityQueue<shoes>(10001, comparator);
I tried adding some shoes and see how it will turn out我试着加了一些鞋子,看看结果如何
list.add(new shoes(56.0, "Nike"));
list.add(new shoes(47.0, "Addidas"));
list.add(new shoes(93.0, "Puma"));
list.add(new shoes(3.0, "Vans"));
Test it in Main在 Main 中测试
for(int i = 0; i < list.size(); i++){
System.out.println(list.poll().getID());
}
//3.0 47.0
Only ID with 3.0 and 47.0 has been registered.仅注册了 3.0 和 47.0 的 ID。 Is there something wrong with my Comparator?我的比较器有问题吗?
It seems like it will only return the first 2 ID and ignore the rest, but when I call upon list.size()
it returns 4, which is correct.似乎它只会返回前 2 个 ID 而忽略其余的 ID,但是当我调用list.size()
它返回 4,这是正确的。 I can't locate the problem.我找不到问题所在。
You can create the PriorityQueue
and in the constructor put comparator code.您可以创建PriorityQueue
并在构造函数中放置比较器代码。
Example:例子:
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(10, new Comparator<Integer>()
{
@Override
public int compare(Integer o1, Integer o2)
{
// Logic here
return 0;
}
});
You can create a custom comparator inline during PriorityQueue instantiation.您可以在 PriorityQueue 实例化期间内联创建自定义比较器。
Assuming your Shoe class looks like the following:假设您的 Shoe 类如下所示:
public class Shoe {
private double size;
private String brand;
public Shoe(double size, String brand) {
this.size = size;
this.brand = brand;
}
public double getSize() {
return size;
}
}
You can create a PriorityQueue that orders the shoes by size by doing the following:您可以通过执行以下操作来创建一个按尺码对鞋子进行排序的 PriorityQueue:
PriorityQueue<Shoe> shoePQ = new PriorityQueue<>(10000, new Comparator<Shoe>() {
@Override
public int compare(Shoe s1, Shoe s2) {
return s1.getSize()-s2.getSize();
});
}
This will order the shoes smallest to largest.这将使鞋子从小到大排序。 If you wanted the reverse order, you would replace the body of compare()
with return s2.getSize()-s1.getSize();
如果你想要相反的顺序,你可以用return s2.getSize()-s1.getSize();
替换compare()
的主体return s2.getSize()-s1.getSize();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.