Consider the case where you retrieve a list of many objects which have a status code attached. There may be many different status codes, and you need to fish through the list of codes and display the object differently, based on the priority. So for instance, an object may have many tasks attached, each of which has an associated priority. You need to display the object in a
certain manner depending on the outstanding task with the highest priority.
A combination of enums and PriorityQueues make this easy. Firstly, we can create an enum to represent the status codes for an outstanding item:
Next, we generate a random list of Status instances and add them to a PriorityQueue instance:
There are a couple of features that make this interesting:
- Java’s Priority Queue implementation sorts by the results of
compareTo(). Hence, your candidate objects must implement
Comparable, and you need to write boilerplate comparison code. Except…
- …When you use an enum. Enums implement Comparable directly, and their comparison order is based on the order of declaration of the enumeration instances. Thus, you just need to declare your enumeration in order of priority (highest first), and let the queue handle the rest.