



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




/** array implementation of LinearList / package dataStructures; import java.util.; // has Iterator interface import utilities.*; // has array resizing class
public class ArrayLinearList implements LinearList { // data members protected Object [] element; // array of elements protected int size; // number of elements in array // constructors and other methods come here }
/** create a list with initial capacity initialCapacity
/** create a list with initial capacity 10 */ public ArrayLinearList() {// use default capacity of 10 this(10); }
public Object remove(int index) { checkIndex(index);
// valid index, shift elements with higher index Object removedElement = element[index]; for (int i = index + 1; i < size; i++) element[i-1] = element[i];
element[--size] = null; // enable garbage collection return removedElement; }
public void add(int index, Object theElement) { if (index < 0 || index > size) // invalid list position throw new IndexOutOfBoundsException ("index = " + index + " size = " + size);
// valid index, make sure we have space if (size == element.length) // no space, double capacity element = ChangeArrayLength.changeLength1D(element, 2 * size);
// shift elements right one position for (int i = size - 1; i >= index; i--) element[i + 1] = element[i];
element[index] = theElement;
size++; }
public String toString() { StringBuffer s = new StringBuffer("["); // put elements into the buffer for (int i = 0; i < size; i++) if (element[i] == null) s.append("null, "); else s.append(element[i].toString() + ", "); if (size > 0) s.delete(s.length() - 2, s.length()); // remove last ", " s.append("]"); // create equivalent String return new String(s); }