//---------------------------------------------------------------------- // ArrayStringLog.java by Dale/Joyce/Weems Chapter 2 // // Implements StringLogInterface using an array to hold the strings. // // ajg version: formatting changes; protected->private; if-then-else; ++ // while-->for; methods reordered //---------------------------------------------------------------------- package ch02.stringLogs; public class ArrayStringLog implements StringLogInterface { private String name; // name of this StringLog private String[] log; // array that holds strings private int lastIndex = -1; // index of last string in array public ArrayStringLog(String name, int maxSize) { // Precondition: maxSize > 0 this.name = name; log = new String[maxSize]; } static final int DEFAULT_MAX_SIZE = 100; public ArrayStringLog(String name) { this(name, DEFAULT_MAX_SIZE); } public void insert(String s) { // Precondition: This StringLog is not full. log[++lastIndex] = s; } public void clear() { for (int i=0; i<=lastIndex; i++) log[i] = null; lastIndex = -1; } public boolean isFull() { return lastIndex == (log.length - 1); } public int size() { return (lastIndex + 1); } public String getName() { return name; } public boolean contains(String element) { for (int location=0; location<=lastIndex; location++) if (element.equalsIgnoreCase(log[location])) return true; return false; } public String toString() { // Returns a nicely formatted string representing this StringLog. String ans = "Log: " + name + "\n\n"; for (int i=0; i<=lastIndex; i++) ans += (i+1) + ". " + log[i] + "\n"; return ans; } } // Local Variables: // compile-command: "cd ../..; javac ch02/stringLogs/ArrayStringLog.java" // End: