//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 in 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 = ""; /**** to be filled in ****/ return str; } public String [] getStrings(){ //return array of strings return this.theList; } public boolean setString(int x, String str){ //sets the string x to str (returns false if it could not set x) /**** to be filled in ****/ return true; } public boolean deleteString(int x){ //removes the string x from the list, shifts everything after it to lower value //(returns false if it could not delete x) /**** to be filled in ****/ return true; } public int addString(String str){ //adds a String to the list, and returns the index for the new String /**** to be filled in ****/ return 0; } public String toString() { //returns a String representation of the Object String returnStr = ""; for (int i = 0; i < theList.length; i++){ returnStr += i + ":" + 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; /**** to be filled in ****/ //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 = null; /**** to be filled in ****/ return other; } public static void main (String [] args) { //main class method being used to test class/objects String [] aString = {"OOP", "Today is Wed.", "Andy"}; ArrayString as = new ArrayString(aString); System.out.println(as.toString()); //The code below demonstrates how an iterator for loop deals with objects //each loop str points to a String from the testAr //when we set str equal to another String (another Object), // we are only changing what str points to for that loop // we are not changing what an elements of testAr is actually pointing to, // so it remains unchanged String [] testAr = as.getStrings(); for (String str: testAr){ str = "nothing"; } System.out.println(testAr[0]); //You can not change which object is being pointed to through a iterator for loop //However, you can ask the object itself to change values within it. } }