/** * Ordered String Bag Collection Class * Collection of Strings maintained in sorted order at all times * CSE 142 lecture, 2/03. HP */ public class OrderedStringBag { // instance variables private String[] strings; // Strings in this StringList are stored in private int numStrings; // strings[0..numStrings-1], and the strings // are stored in ascending order: strings[0] // <= strings[1] <= ... <= strings[numStrings-1] /** Construct a new empty StringList with the given capacity */ public OrderedStringBag(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) { return false; } else { // Room for str. Shift all larger strings // one position to the right int pos = numStrings; while (pos > 0 && strings[pos-1].compareTo(str) > 0) { strings[pos] = strings[pos-1]; pos--; } // insert str at position to the left of larger strings strings[pos] = str; numStrings++; return true; } } /** 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]; } } /** Return whether this StringList contains str */ public boolean contains(String str) { // binary search // invariant: strings[0..L] <= str, strings[R..numStrings-1] > str, and // strings[L+1..R-1] have not been examined yet int L = -1; int R = numStrings; while (L+1 != R) { int mid = (L + R) / 2; if (strings[mid].compareTo(str) <= 0) { L = mid; } else { R = mid; } } // Found if L >= 0 and strings[L] matches str return (L >= 0 && strings[L].equals(str)); } /** 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; } }