1

I have a PriorityQueue called Incoming, that contains objects of type Vehicle.

You can call the method getFuelLevel() on all Vehicles.

What I want to do is to sort Incoming, so that the Vehicles with the least fuel are given a higher priority and are put at the front of the Queue.

I'm assuming I have to use a Comparator here but have no idea how to do it.

Connor Cartwright
  • 385
  • 2
  • 3
  • 14

2 Answers2

1

One thing that I always do when using a PriorityQueue with my own class is to make that class implement Comparable<Class>. With this, rather than needing to implement a Comparator, all you need to implement is the int compareTo(Class o) method in the class which returns "a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."

In your case, this would return 1 if the Vehicles has less fuel than the Vehicles inputed, 0 if the two have the same, and -1 if the Vehicles has more fuel than the one inputed.

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

robertzi7
  • 26
  • 2
1

The PriorityQueue class has a constructor that takes a Comparator as an argument. You can construct a PriorityQueue by providing your specific Comparator as

PriorityQueue<Vehicle> queue = new PriorityQueue<Vehicle>(initialCapacity, new Comparator<Vehicle> {
    int compare(Vehicle a, Vehicle b) {
        return a.getFuelLevel() - b.getFuelLevel();
    }
});
tonga
  • 11,749
  • 25
  • 75
  • 96
  • Can you take a look at my use of a PriorityQueue in this question? http://stackoverflow.com/questions/28800287/how-to-restore-the-priorityqueue-to-its-initial-state-before-the-method-call?noredirect=1#comment45875800_28800287 – committedandroider Mar 02 '15 at 00:44