Java Reference
In-Depth Information
What if an application requires us to remove an entry from a list but retain the entry for
another purpose? Our specification of
remove
would force us to first use
getEntry
to obtain the
entry and then use
remove
to remove it from the list. We could refine the specification of
remove
to
return the object removed from the list. To use this revised version of
remove
, we would write a
pseudocode statement such as
oldEntry3 = myList.remove(3)
This change makes
remove
more versatile, as the client could either save or ignore the returned entry.
We can replace the third entry
b
of our list with
f
by writing
myList.replace(3, f)
No other entries move or change. We could refine the specification of
replace
to return the object
that was replaced. So if we wrote
ref = myList.replace(3, f)
ref
would reference the former entry
b
.
Note:
The objects in an ADT list have an order determined by the client of the list. To add,
remove, or retrieve an entry, you must specify the entry's position within the list. The first
entry in the list is at position 1.
12.6
The previous specifications and examples ignore some difficulties that might arise during the use of
the ADT list:
•
The operations
add
,
remove
,
replace
, and
getEntry
are well behaved when the given
position is valid for the current list. What happens when one of these operations receives
an invalid position number?
•
The methods
remove
,
replace
, and
getEntry
are not meaningful for empty lists. What happens
when an empty list executes one of these operations?
As usual, we must decide how to handle these conditions and refine our specifications. The documentation
for the ADT list should reflect both these decisions and the detail that the previous examples demonstrate.
As a reminder, we repeat the following note from Chapter 1.
Note:
A first draft of an ADT's specifications often overlooks or ignores situations that you
really need to consider. You might intentionally make these omissions to simplify this first
draft. Once you have written the major portions of the specifications, you can concentrate on
the details that make the specifications complete.
12.7
The Java interface in Listing 12-1 contains the methods for an ADT list and detailed comments that
describe their behaviors. These comments address the situations we raised in the previous segment.
The items in the list will be objects of the same class or classes related by inheritance.
LISTING 12-1
The interface
ListInterface
/** An interface for the ADT list.
Entries in the list have positions that begin with 1.
*/