Java 5 Enums and Priority Queues

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:




package uk.co.researchkitchen.tiger;

public enum Status {
  HIGH("red"),
  MEDIUM("amber"),
  LOW("green");
  
  private String color;
  
  public String getColor() { return color; }
  
  Status(String color) {
    this.color = color;
  }
}

Next, we generate a random list of Status instances and add them to a PriorityQueue instance:



package uk.co.researchkitchen.tiger;

import java.util.PriorityQueue;
import java.util.Random;

public class SortStatuses {
  
  public static void main(String[] args) {
    PriorityQueue<Status> queue = new PriorityQueue<Status>();
    
    Status statuses[] new Status[] { Status.HIGH, Status.MEDIUM, Status.LOW};
    Random generator = new Random();
    
    // Pretend list of 100 items, each with a different status code
    for (int i = 0; i < 100; ++i) {
      queue.addstatusesgenerator.nextInt(3) ] );
    }
    
    /*for (Status status : queue) {
      System.out.println(status);
    }*/
    
    System.out.println(queue.peek());
  }

}

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.

Leave a Reply