I created a class called Foo. Foo has three fields, which are all ints: x, y, and z. I want to make a PriorityQueue<Foo> which prioritizes the Foo objects differently in different situations. For instance, I might want to prioritize by x value, or maybe by y value, or maybe by z. But I won’t know which value I want to prioritize by until runtime. I’ve heard you can use comparators to somehow impose an ordering on the fly, which I think would be perfect here.
I’m confused as to exactly how I would do this though. Could someone please show me an example if say I wanted to prioritize on x using a comparator (without having to override the compareTo function in my Foo class)?
Thank you very much.
A comparator is a parameterized interface that allows you to define how two instances of the parameterized type can be compared. let’s assume you have the following class
Then to define a comparator that orders elements based on their x value then y then z we’d do the following
Similarly you can define comprators that compare elements based first on their y value then x the z…etc
Finally at runtime you can instantiate a PriorityQueue with that comparator
For more information take a look at the priority queue javadoc as well as the comparator javadoc
Edit: Please see @buritos comment regarding integer overflow.