//------------------------------------------------------------------------- // ArrayIndexedList.java by Dale/Joyce/Weems Chapter 6 // // Implements the IndexedListInterface using an array. // // All methods accepting an index Throw IndexOutOfBoundsException if // index < 0 or index > numElements. // // Null elements are not permitted on a list. // // ajg version: DWC, size()->numElements, bug fixed in remove(), // BOUNDED so isFull() and ListOverflowException replace enlarge() //---------------------------------------------------------------------------- package ch06.lists; public class ArrayIndexedList extends ArrayUnsortedList implements IndexedListInterface { public ArrayIndexedList(T[] list) { super(list); } // Add element at position index; slide other elements down. public void add(int index, T element) { if ((index < 0) || (index > size())) throw new IndexOutOfBoundsException(msg(index, "add")); if (numElements == list.length) throw new ListOverflowException("Helpful message."); for (int i=numElements++; i>index; i--) list[i] = list[i-1]; list[index] = element; } public boolean isFull() { return numElements == list.length; } // Replace element at position index and return the replaced element. public T set(int index, T element) { if ((index < 0) || (index >= size())) throw new IndexOutOfBoundsException(msg(index, "add")); T ans = list[index]; list[index] = element; return ans; } // Return the element at position index. public T get(int index) { if ((index < 0) || (index >= size())) throw new IndexOutOfBoundsException(msg(index, "add")); return list[index]; } // If this list contains an element e such that e.equals(element), // Return index of first element e with e.equals(element) or -1 if no such e public int indexOf(T element) { return (find(element)) ? location : -1; } // Remove and return element at position index; slide other elements up public T remove(int index) { if ((index < 0) || (index >= size())) throw new IndexOutOfBoundsException(msg(index, "add")); T ans = list[index]; for (int i=index; i<--numElements; i++) list[i] = list[i+1]; list[numElements] = null; // optional return ans; } // Return a nicely formatted string that represents this list. public String toString() { String listString = "List:\n"; for (int i = 0; i < numElements; i++) listString = listString + "[" + i + "] " + list[i] + "\n"; return listString; } private String msg(int index, String method) { // Produce illegal indexXS msg return "Illegal index of " + index + " passed to ArrayIndexedList " + method + "() method.\n"; } } // Local Variables: // compile-command: "cd ../..; javac ch06/lists/ArrayIndexedList.java" // End: