/** * String List Collection Class * Demonstration using arrays to implement a list * CSE 142 lecture, 2/03. HP */ public class StringList { // instance variables private String[] strings; // Strings in this StringList are stored in private int numStrings; // strings[0..numStrings-1] /** Construct a new empty StringList with the given capacity */ public StringList(int capacity) { strings = new String[capacity]; numStrings = 0; } /** * Add str to this StringList if room available and return true; * otherwise return false */ public boolean add(String str) { if (numStrings < strings.length) { strings[numStrings] = str; numStrings++; return true; } else { return false; } } /** Return the current size of this StringList */ public int size() { return numStrings; } /** Remove all strings from this StringList */ public void clear() { // null out string references so the space can be recycled if not otherwise in use for (int k = 0; k < numStrings; k++) { strings[k] = null; } // record that the list is now empty numStrings = 0; } /** Return the string at position pos, or null if pos is out of bounds */ public String get(int pos) { if (pos < 0 || pos >= numStrings) { return null; } else { return strings[pos]; } } /** * Store str in this StringList at position pos if pos is in bounds * and return the previous string at that position. If pos is out of * bounds, return null without altering this StringList. */ public String set(int pos, String str) { if (pos < 0 || pos >= numStrings) { return null; } else { String oldString = strings[pos]; strings[pos] = str; return oldString; } } /** Return whether this StringList contains str */ public boolean contains(String str) { // linear search for (int k = 0; k < numStrings; k++) { if (str.equals(strings[k])) { return true; } } return false; } /** Return a string representation of this StringList */ public String toString() { String result = "["; if (numStrings > 0) { result = result + strings[0]; for (int k = 1; k < numStrings; k++) { result = result + ", " + strings[k]; } } result = result + "]"; return result; } }