Return to the lecture notes index

Lecture #30 (Friday, Dec 1, 2006)

Daily Excercise Two

Today we did our second daily excercise in order to get more familiar with actual programming. You were asked to write a equals() method, and a find and shift to end method. This finds the item and then shifts everything after it to left, and puts the item into the last slot.

// Turn in, as a lab, into the "daily2" directory

class SortableArrayCollection {

  private Comparable[] items;
  private int count;
  
  private static final int DEFAULT_SIZE = 100;
  private static final int GROWTH_COEFF = 2;
  
  
  private void grow() {
    Comparable[] biggerArray = new Comparable[GROWTH_COEFF * items.length];
  
    for (int index=0; index < items.length; index++)
      biggerArray[index] = items[index];
  
    items = biggerArray;
  }
  
  
  public SortableArrayCollection(int size) {
    items = new Comparable[size];
    count = 0;
  }
  
  
  public SortableArrayCollection() {
    items = new Comparable[DEFAULT_SIZE];
    count = 0;
  }
  
  
 // 1. Write equals() -- compare each and every item
  	public boolean equals(Object o) {
         SortableArrayCollection sac = (SortableArrayCollection) o;
        
	//If they don't have the same number of items, than they aren't equal
        if (count != sac.count) {
            return false;       
        }
        
	//Checks to make sure that every item at index is equal to the 
        // Item in the other collection at the same index
        // If any item is not equal, return false
        for (int index=0; index < count; index++) {
        	if(!items[index].equals(sac.items[index]))
		     return false;
        }

	//If we got all the way through, that means they were all equal, so return true
        return true;
    }


 // 2. Write void findAndShiftToEnd(Comparable c) -- does nothting if not found
  	public void findAndShiftToEnd(Comparable c) {
  		int index;

		//Find the item's index
  		for (index=0; index < count; index++) {
  			if (items[index].equals(c))
  				break;
  		}

		//Shifts everything after c to the left
  		for (; iindex < count-1; index++) {
  			items[index] = items[indexTwo+1];
  		}
  		
		//Puts c in the last spot	
  		items[count-1] = c;  		
  	}
}