Methods in the Interface
LABORATORY 4: Prelab Exercise Name
Hour/Period/Section Date
You can implement a list in many ways. Given that all the elements in a list are of the same type, and that the list structure is linear, an array seems a natural choice.
Arrays have a limited capacity. An important characteristic of arrays in Java is that the size of the array is held in a final public data member called length in the array object. Unlike the length method in the class String, this is a data member, not a method, so there are no paren- theses following length. For example, consider the declaration
int scores = new int[10];
After this declaration, scores.length is 10. Note that although length is public, its value cannot be changed because is it also declared as final.
Valid values for the array index range from 0 through one less than the length of the array. Java safely handles invalid array index references. Trying to access an invalid array index will cause the program to terminate with an ArrayIndexOutOfBoundsException.
The List ADT has a common set of methods that any List implementation should provide. For example, the Point List ADT in Laboratory 2 has a set of commands nearly identical to the List ADT in this laboratory. Some future laboratories will also implement this List ADT.
In Java, one approach to identifying these common methods that may be used for a variety of list implementations is to define an interface. An interface definition is similar to a class defi- nition, but
• An interface does not (and cannot) have any data members.
• An interface can specify a set of constants—the modifiers public static final need not be specified since they are implicit for constants in an interface.
• All methods are automatically abstract—they don’t have an implementation. The header of each method, including its parameter list, is simply followed by a semicolon.
• All methods are automatically public. Note that the class must explicitly declare the imple- mented interface method as public, however.
• An interface cannot be instantiated—it is not a class and all its methods are abstract.
TEAM
FLY
The List interface is in the file List.javaand is defined as follows:
interface List // Constants & Methods common to List ADTs {
// Default maximum list size - a constant public static final int DEF_MAX_LIST_SIZE = 10; // List manipulation operations
public void insert(Object newElement); // Insert Object after cursor public void remove( ); // Remove element at cursor public void replace (Object newElement); // Replace element at cursor public void clear( ); // Remove all elements from list // List status operations
public boolean isEmpty( ); // Returns true if list is empty public boolean isFull( ); // Returns true if list is full public boolean gotoBeginning( ); // Moves cursor to beginning of list public boolean gotoEnd( ); // Moves cursor to end of list
public boolean gotoNext( ); // Moves cursor to next element in list public boolean gotoPrior( ); // Moves cursor to preceding element public Object getCursor( ); // Returns the element at the cursor public void showStructure( ); // Outputs the elements in a list.
// for testing/debugging purposes only } // interface List
Any class that implements List, as the class ListArray does in Step 1 below, is required to provide a public implementation for every method listed in the interface List. The Java com- piler will produce errors if any of the methods in the interface are not given a definition in the implementing class.
Step 1: Implement the operations in the List ADT using an array to store the list elements. Lists change in size as elements are added, removed, and the like. Therefore, you need to store the actual number of elements in the list (size), along with the list elements themselves (element). The maximum number of elements our list can hold can be determined by referenc- ing length in the array object—more specifically, in our case, by referencing element.length. You also need to keep track of the cursor array index (cursor).
Base your implementation on the following incomplete definitions from the file ListArray.jshl. You are to fill in the Java code for each of the constructors and methods in which the implementation braces are empty, only partially filled (noted by “add code here …”), or where an entire method or set of methods from the interface needs to be inserted (noted by “insert method … here”).
class ListArray implements List // Array based list class {
// Data Members
private int size, // Actual number of elements in the list cursor; // Cursor array index
LABORATORY 4
87
public ListArray(int maxNumber) // Constructor: specific size{ } // Class methods
private void setUp (int maxNumber) // Called by constructors only { }
// --- Insert method implementations for the interface list here --- // } // class ListArray
Step 2: Save your implementation of the List ADT in the file ListArray.java. Be sure to docu- ment your code.
The following sample program (in the file Sample.java) uses the array implementation of the operations in the List ADT (in the file ListArray.java) to read in a list of integer samples and compute their sum. Especially notice how conversions are made between a primitive (int) to an Object (Integer) and back again.
import java.io.*; class Sample {
public static void main ( String [] args ) throws IOException {
ListArray samples = new ListArray(100);// Set of samples int newSample, // Input sample
total = 0; // Sum of the input samples //--- // Instantiate several classes for processing input.
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer tokens = new StreamTokenizer(reader); // Read in a set of samples from the keyboard.
System.out.print("Enter list of samples (end with eof) : ");
// Keep reading as long as text (the word eof) has not been entered while ( tokens.nextToken( ) != tokens.TT_WORD )
{
newSample = (int)tokens.nval;
// insert an Object — an int converted to an Integer samples.insert(new Integer(newSample));
}
// Sum the samples and output the result.
if ( samples.gotoBeginning() ) // Go to beginning of list // Add element to running sum
// must cast Object to Integer, then convert Integer to int do
total += ((Integer)samples.getCursor( )).intValue( ); while ( samples.gotoNext() ); // Go to next element (if any) System.out.println("Sum is " + total);
} // main } // class Sample
LABORATORY 4: Bridge Exercise
NameHour/Period/Section Date
Check with your instructor as to whether you are to complete this exercise prior to your lab period or during lab.
The test programs that you used in Laboratories 1 and 3 consisted of a series of tests that were hardcoded into the programs. Adding a new test case to this style of test program requires changing the test program itself. In this and subsequent laboratories, you use a more flexible kind of test program to evaluate your ADT implementations, one in which you specify a test case using commands, rather than code. These interactive, command-driven test programs allow you to check a new test case by simply entering a series of keyboard commands and observing the results.
The test program in the file TestListArray.java, for instance, supports the following commands.
Command Action
+x Insert element x after the cursor.
- Remove the element marked by the cursor.
=x Replace the element marked by the cursor with element x. @ Display the element marked by the cursor.
N Go to the next element. P Go to the prior element.
< Go to the beginning of the list. > Go to the end of the list.
E Report whether the list is empty. F Report whether the list is full.
C Clear the list.