Java Reference
In-Depth Information
int newIndex = newPosition - 1;
int lastIndex = numberOfEntries - 1;
// move each entry to next higher index, starting at end of
// list and continuing until the entry at newIndex is moved
for ( int index = lastIndex; index >= newIndex; index--)
list[index + 1] = list[index];
} // end makeRoom
Notice that the add method enforces the precondition of makeRoom . While testing makeRoom ,
however, we can enable the assertion to be sure.
FIGURE 13-4
Making room to insert Carla as the third entry in an array
Bob
Doug
Haley
Alice
Bob
Alice
Doug
Haley
Haley
Alice
Bob
Doug
Doug
Haley
Carla
Alice
Bob
Doug
Haley
Question 4 You could implement the first add method, which adds an entry to the end of
the list, by invoking the second add method, as follows:
public void add(T newEntry)
{
add(numberOfEntries + 1, newEntry);
} // end add
Discuss the pros and cons of this revised approach.
Question 5 Suppose that myList is a list that contains the five entries a b c d e .
a.
What does myList contain after executing myList.add(5, w) ?
b.
Starting with the original five entries, what does myList contain after executing
myList.add(6, w) ?
c.
Which of the operations in Parts a and b of this question require entries in the array to shift?
Question 6 If myList is a list of five entries, each of the following statements adds a new
entry to the end of the list:
myList.add(newEntry);
myList.add(6, newEntry);
Which way requires fewer operations?
Search WWH ::




Custom Search