The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

A Priority Queue Client

The implementation of Priority Queue is written entirely in terms of Comparable objects, but there is no such thing as a Comparable object! Go ahead, try to create one:

    Comparable comp = new Comparable ();       // ERROR

You'll get a compile-time message that says something like "java.lang.Comparable is an interface. It can't be instantiated." In Java, abstract classes are called interfaces. I have avoided this word so far because it also means several other things, but now you have to know.

Why can't abstract classes be instantiated? Because an abstract class only specifies requirements (you must have a compareTo method); it does not provide an implementation.

To create a Comparable object, you have to create one of the objects that belongs to the Comparable set, like Integer. Then you can use that object anywhere a Comparable is called for.

        PriorityQueue pq = new PriorityQueue ();
        Integer item = new Integer (17);
        pq.insert (item);

This code creates a new, empty Priority Queue and a new Integer object. Then it inserts the Integer into the queue. insert is expecting a Comparable as a parameter, so it is perfectly happy to take an Integer. If we try to pass a Rectangle, which does not belong to Comparable, we get a compile-time message like, "Incompatible type for method. Explicit cast needed to convert java.awt.Rectangle to java.lang.Comparable."

That's the compiler telling us that if we want to make that conversion, we have to do it explicitly. We might try to do what it says:

    Rectangle rect = new Rectangle ();
    pq.insert ((Comparable) rect);

But in that case we get a run-time error, a ClassCastException. When the Rectangle tries to pass as a Comparable, the run-time system checks whether it satisfies the requirements, and rejects it. So that's what we get for following the compiler's advise.

To get items out of the queue, we have to reverse the process:

    while (!pq.empty ()) {
        item = (Integer) pq.remove ();
        System.out.println (item);

This loop removes all the items from the queue and prints them. It assumes that the items in the queue are Integers. If they were not, we would get a ClassCastException.

Last Update: 2011-01-24