Notes for June 20, 2005

This document supplements the readings, so there won't be everything we talked about in class on this page.

Here is the equals method we wrote together in class.

public boolean equals(int[] a1, int[] a2)
{
    if (a1.length != a2.length) {
        return false;
    }

    // else clause unnecessary, because we are
    // guaranteed that a1.length == a2.length

    for (int i = 0; i < a1.length; i++) {
        if (a1[i] != a2[i]) {
            return false;
        }
    }

    return true;
}
Incidentally, Java has a class with this method. See the Arrays class. You would use it something like:
boolean areEqual = Arrays.equals(a1, a2);
Later in the quarter, we'll talk about reading the documentation for the Java API (Application Programming Interface). People at Sun did a really good job or writing useful methods so programmers don't have to reinvent the wheel. Unfortunately for you though, since this is a beginner's programming class, we'll have to rewrite a lot of stuff, so you really understand how they work.

Here is the printArray method, along with the fix, so it does not print too many commas.

public void printArray(int[] a1)
{    
    System.out.print("[");
    for (int i = 0; i < a1.length; i++) {
        System.out.print(a1[i]);
	
	// print comma if did not just print last
	// element (i.e. i < a1.length - 1);
        if (i < a1.length - 1) {
            System.out.print(",");
        }
    }
    System.out.println("]");
}