Test Yourself #2
Question 1:
private void expandArray() {
// allocate an array of twice the size of the "items" array
// copy all values from "items" to the new array
// assign "items" to refer to the new array
Object[] tmp = new Object[items.length*2];
System.arraycopy(items, 0, tmp, 0, items.length);
items = tmp;
}
Question 2:
The moveItemsRight method can be implemented using a loop to
move the items, like this:
private void moveItemsRight(int start) {
// move all of the items in the sequence, starting with the item with
// index "start", one place to the right (i.e., move items[start] to
// items[start+1], move items[start+1] to items[start+2], etc
for (int k=numItems-1; k>=start; k--) {
items[k+1] = items[k];
}
}
It can also be implemented using System.arraycopy, like this:
private void moveItemsRight(int start) {
// move all of the items in the sequence, starting with the item with
// index "start", one place to the right (i.e., move items[start] to
// items[start+1], move items[start+1] to items[start+2], etc
System.arraycopy(items, start, items, start+1, numItems-start);
}