Programming and Problem Solving with Java

(やまだぃちぅ) #1
11.2 List Class | 535

from the documentation that the item may or may not be in the list. If we find it, how do we re-
move it? We shift each item that comes after the one being deleted forward by one array slot.


public voiddelete(String item)
// Removes item from the list if it is there
// Implements "delete if there" semantics
{
int index = 0;
booleanfound = false;
while(index < numItems && !found)
{
if (listItems[index].compareTo(item) == 0)
found = true;
else
index++;
}
if (found)
{
for (int count = index; count < numItems-1; count++)
listItems[count] = listItems[count+1];
numItems--;
}
}


The resetListmethod is analogous to the open operation for a file in which the file
pointer is positioned at the beginning of the file, so that the first input operation accesses
the first component of the file. Each successive call to an input operation gets the next item
in the file. Therefore resetListmust initialize currentPosto the first item in the list. Where
is the first item in an array-based list? In position 0. The getNextItemoperation is analogous


shiftUp
(index is the location of the item to be deleted)
Set listItems[index] to listItems[index + 1]
Set listItems[index + 1] to listItems[index + 2]
.
.
.
Set listItems[numItems – 2] to listItems[numItems – 1]

delete
Set index to location of item to be deleted if found
iffound
Shift remainder of list up
Decrement numItems
Free download pdf