Java Reference
In-Depth Information
One of the most powerful advantages that generics bring to programming is the ability to
construct reliable, reusable code. As mentioned at the start of this chapter, many algorithms
are the same no matter what type of data they are used on. For example, a queue works the
same way whether that queue is for integers, strings, or File objects. Instead of creating a
separate queue class for each type of object, you can craft a single, generic solution that
can be used with any type of object. Thus, the development cycle of design, code, test, and
debug occurs only once when you create a generic solution—not repeatedly, each time a
queue is needed for a new data type.
In this project, you will adapt the queue example that has been evolving since Try This
5-2 , making it generic. This project represents the final evolution of the queue. It includes
a generic interface that defines the queue operations, two exception classes, and one queue
implementation: a fixed-size queue. Of course, you can experiment with other types of gen-
eric queues, such as a generic dynamic queue or a generic circular queue. Just follow the
lead of the example shown here.
Like the previous version of the queue shown in Try This 9-1 , this project organizes the
queue code into a set of separate files: one for the interface, one for each queue excep-
tion, one for the fixed-queue implementation, and one for the program that demonstrates it.
This organization reflects the way that this project would normally be organized in the real
world.
1. The first step in creating a generic queue is to create a generic interface that describes
the queue's two operations: put and get. The generic version of the queue interface is
called IGenQ and it is shown here. Put this interface into a file called IGenQ.java .
Notice that the type of data stored by the queue is specified by the generic type para-
meter T .
2. Next, create the files QueueFullException.java and QueueEmptyException.java .
Put in each file its corresponding class, shown here:
Search WWH ::




Custom Search