我有一个叫Incoming
的PriorityQueue
,它包含Vehicle
类型的对象。Java优先级队列排序
您可以拨打所有Vehicles
上的方法getFuelLevel()
。
我想要做的是对Incoming
进行排序,以便Vehicles
的fuel
的优先级更高,并放置在队列的前端。
我假设我必须在这里使用Comparator
,但不知道该怎么做。
我有一个叫Incoming
的PriorityQueue
,它包含Vehicle
类型的对象。Java优先级队列排序
您可以拨打所有Vehicles
上的方法getFuelLevel()
。
我想要做的是对Incoming
进行排序,以便Vehicles
的fuel
的优先级更高,并放置在队列的前端。
我假设我必须在这里使用Comparator
,但不知道该怎么做。
在我自己的课程中使用PriorityQueue
时,我总是这样做的一件事是让该课程实现Comparable<Class>
。有了这个,不需要实现一个比较器,所有你需要实现的是类中的int compareTo(Class o)
方法,该方法返回“负整数,零或正整数,因为该对象小于,等于或大于指定的对象“。
在你的情况,这将返回1,如果Vehicles
有更少的燃料比Vehicles
inputed,0如果两者具有相同的,和-1,如果Vehicles
有更多的燃料比一个inputed。
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
的PriorityQueue
类有一个构造函数一个Comparator
作为参数。您可以通过提供构建PriorityQueue
您的具体Comparator
作为
PriorityQueue<Vehicle> queue = new PriorityQueue<Vehicle>(initialCapacity, new Comparator<Vehicle> {
int compare(Vehicle a, Vehicle b) {
return a.getFuelLevel() - b.getFuelLevel();
}
});
你可以看看我在这个问题中使用PriorityQueue吗? http://stackoverflow.com/questions/28800287/how-to-restore-the-priorityqueue-to-its-initial-state-before-the-method-call?noredirect=1#comment45875800_28800287 – committedandroider
http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue – user3159253
这是'java.util中。 PriorityQueue'或者你正在编写你自己的实现?如果您正在编写自己的文章,请尝试使用堆。 – McLovin
有一个很好的例子:http://www.journaldev.com/1642/java-priority-queue-priorityqueue-example演示如何在排序中使用比较器。 – Alan