|
|
A List is a doubly-linked list of objects. From the user's point of view, it is simply an ordered sequence of elements which can be examined, read from, added to, deleted from, or traversed in two directions. It can also be compared with other Lists. The elements of Lists are indexed; and the indices range from 0 through N - 1 where N is the number of elements in the List. Positions between elements in the List are also indexed (from 0 through N) where the ith position in the List is just before the ith element.
Lists are homogeneous and generic; that is, each List contains only one type of object, and you specify what that type will be when you declare the List. For most applications, homogeneous Lists are entirely appropriate. Those applications that do require heterogeneous Lists can be handled with a little extra effort (and usually an extra level of indirection). Compile-time enforcement of homogeneity prevents a whole class of run-time errors involving the appearance on a List of an object with inappropriate type.
Lists can be declared as static or automatic variables or created, using the
new
operator, on the free store.
The semantics
of operations on Lists are modeled after that for fixed-size objects.
Thus, assignment
is by value, and Lists can be used as function arguments
and result types with expected results.
As usual in C and C++, changes to the formal argument in the called function
do not affect the actual argument in the caller.
A reference or a pointer
to a List can, of course, be passed to a function
to avoid copying or to effect
a change in the List being passed.
The following example shows how the List class can be used. It is a function that takes a model String and a List of Strings as arguments, and returns a copy of the List with all instances of the model removed.
1: List<String> 2: remove(String model, List<String> inList) 3: { 4: List<String> outList; 5: String temp; 6: while ( inList.get(temp) ) 7: if ( temp != model ) 8: outList.put(temp); 9: return outList; 10: }
In this example
String
and List<String>
are types, so line 1
defines the return type of the function, line 2 defines the
name of the function and its arguments and their types,
and lines 4 and 5 are automatic
variable declarations.
In line 6, the get()
function
removes the first String from inList
, assigns it
to temp
and returns TRUE
as long as inList
is non-empty.
When inList
is empty, the get()
function returns FALSE, ending the while
loop.
In line 7, temp
is compared to
model
, and if it is different, the
put()
function in line 8 adds it to the end of
outList
.
Thus, in line 9, outList
is the desired result, and the return statement returns it to the caller.