HW2 SAMPLE ANSWERS 1. public String lookupEntry(String name) { int namePosition = find(name); if (namePosition != -1) { DirectoryEntry entry = directoryArray[namePosition]; for (int index = namePosition-1; index >= 0; index--) directoryArray[index+1] = directoryArray[index]; /* OR System.arraycopy(directoryArray, 0, directoryArray, 1, namePosition); */ directoryArray[0] = entry; modified = true; return directoryArray[0].getNumber(); } return null; // if name not found } 2. Doubling the array size yields 10,20,40,80,160,320. Removing entries does not resize, so the final size of the array is 320. 1/2 pt for correct answer 1/2 pt for explanation that's reasonable 3. If we just set the cell to null, when we traverse the array to look for a name or number, we will get a NullPointerException when we hit the null cell since no object reference is there. Examples of this occur in any method that traverses the array and calls a method on an object in each array cell (for example, find). 4. Changes: - add method to PhoneDirectory class for new operation - change processCommands in PDConsoleUI class to add extra menu option - add method to PDConsoleUI class to perform new operation - change processCommands in PDGUI class to add extra menu option - add method to PDGUI class to perform new operation 5. Any of these are ok: A Java interface allow a programmer who uses a class that implements an interface to write code without consulting with the programmer of the class since it follows the definitions provided in the interface. It allows us to remove one class that implements an interface and add in another that implements the same interface without changing our other application code (e.g. in the PhoneDirectory, we have two UIs, but the code treats them as a PDUserInterface throughout). A Java interface enforces that classes that implement the interface must supply the specified methods in order to behave like other classes that also implement the interface. 6. Checked - we must indicate for compiler what we will do if exception is thrown (throws or try/catch) (e.g. IOException) Unchecked - we don't have to write code to deal with these but if they occur the program will still crash (e.g. ArrayIndexOutOfBoundsException, NullPointerException, NumberFormatException, etc) 7. Test cases: element in first position element in last position element somewhere in middle element not in array array has only one element array has no elements element occurs more than once 8. /** Returns the index of the target an array if it occurs or -1 otherwise. @param data array containing the data to search through @param target value that we're looking for in array @return index of the target if found in the array or -1 if not found */