//ArrayString class //Holds any number of strings //A more versatile version of QuadString //which demonstrates Object methods: toString, equals, and clone //9/13/2006 public class ArrayString { //instance variables: String []theList; int numStrings; public ArrayString(String str){ //constructor when only one string is passed on (calls on other constructor) this.theList = new String[1]; this.theList[0] = str; this.numStrings = 1; } public ArrayString(String [] array){ //constructor which takes an array of strings this.theList = array; this.numStrings = array.length; } public ArrayString(){ //constructor which takes in nothing this.numStrings = 0; this.theList = null; } public String getString(int x){ //return string x String str = ""; if ((this.numStrings > x) && (x >= 0)) return this.theList[x]; return null; } public String [] getStrings(){ //sets the string x to str (returns false if it could not set x) return this.theList; } public String toString() { //returns a String representation of the Object String returnStr = ""; for (int i = 0; i < this.numStrings; i++){ returnStr += i + ": " + this.theList[i] + "\n"; } return returnStr; } public boolean equals(Object other){ //compares this object of ArrayString to another //note we do not need else if since it returns at any point that it discovers they are not equal if (!(other instanceof ArrayString)) return false; ArrayString another = (ArrayString)other; if (another.numStrings != this.numStrings) return false; String [] myStrings = this.getStrings(); String [] otherStrings = another.getStrings(); if (otherStrings.length != myStrings.length) return false; for (int i = 0; i < this.numStrings; i++) if (!(myStrings[i].equals(otherStrings[i]))) return false; //all strings are equal so they must be the same return true; } public Object clone() { //create a new object which is the same as "this" ArrayString other = new ArrayString(this.theList.clone());//clone here may not be necessary return (Object)other; } public static void main (String [] args) { //main class method being used to test class/objects String[] arStr = {"bob 1", "mary 2", "this is a test 3", "the forth test line 4"}; ArrayString testAS = new ArrayString(arStr); System.out.println("toString test:\n" + testAS); ArrayString testAS2 = (ArrayString)testAS.clone(); System.out.println("clone test: \n" + testAS2); String maryStr = new String("mary 2"); String [] arStr2 = {"bob 1", maryStr, "this is a test 3", "the forth test line 4"}; String [] arStr3 = {"bob 1", "mary 2", "this s a test 3", "the forth test line 4"}; ArrayString testAS3 = new ArrayString(arStr2); ArrayString testAS4 = new ArrayString(arStr3);//not equal System.out.println("equals test: (T, T, T, F, F)"); System.out.println(testAS.equals(testAS2)); System.out.println(testAS.equals(testAS3)); System.out.println(testAS3.equals(testAS)); System.out.println(testAS.equals(testAS4)); System.out.println(testAS4.equals(testAS)); } }