11.7 Generic Lists | 559
11.7 Generic Lists
In generic lists, the operations are defined, but the types of the objects on the list are not.
Although we called the components of our lists “items,” they are actuallyStrings. Is it possible
to construct a truly general-purpose list where the items can be of any type? For example,
could we have a list ofNameobjects as defined in Chapter 4 or a list ofAddressobjects as defined
in Chapter 6? Yes, we can. All we have to do is declare the objects on the list to beComparable.
What isComparable? It’s a Java interface. Let’s see how we can use it to make our lists generic.
Comparable Interface
In Chapter 5, we defined the Java construct interfaceas a model for a class that specifies the
constants (final fields) and instance methods that must be present in a class that implements
the interface. The Comparableinterface is part of the standard Java class library. Any class
that implements this interface must implement the method compareTo. This method compares
two objects and returns an integer that determines the relative ordering of the two objects
(the instance to which it is applied and the method’s parameter).
intValue = item.compareTo(listItems[index]);
intValueis negative ifitemcomes beforelistItems[index], is 0 if they are equal, and is posi-
tive ifitemcomes afterlistItems[index]. We have used this method to compare strings in the
classes designed in this chapter because theStringclass implements theComparableinterface.
To make ourListclass as generic as possible, we replaceStringwithComparablethroughout
the class. As a consequence, any object of a class that implements theComparableinterface can
be passed as an argument toinsert,delete,orisThere. In addition, the type of the array elements
must be declared as implementingComparableandgetNextItemmust return a value of type
Comparable. Here is the complete abstract classList:
public abstract classList
{
protectedComparable[] listItems; // Array to hold list items
protected intnumItems; // Number of items in the list
protected intcurrentPos; // State variable for iteration
publicList(int maxItems)
// Instantiates an empty list object with room for maxItems items
{
numItems = 0;
listItems = new Comparable[maxItems];
currentPos = 0;
}
publicList()
// Instantiates an empty list object with room for 100 items