CS115 lecture notes, Spring 1999 Week 11, Wednesday How are arrays similar to objects? How are arrays different from objects? Arrays (continued) ------------------ If you use an index that is negative or >= size, you get an ArrayOutOfBoundsException. You can use loops to traverse arrays: int i = 0; while (i<4) { System.out.println (count[i]); i++; } Example: Given an array of doubles, a, how would you make a copy? double[] a = new double[3]; double[] b = a; This copies a reference to the array, which means that a and b are now aliased. To build a new array, we have to use new to allocate space, and a loop to copy the elements of the array. double[] b = new double [3]; int i = 0; while (i < 4) { b[i] = a[i]; i++; } Passing arrays as parameters ---------------------------- Good news. Everything is the same as passing objects as parameters. 1) A reference gets passed 2) Caller and callee have two references to the same object (aliasing) 3) Callee can modify the contents of the array. Example: public static int banana (int[] a) { int i = 0; int grape = 0; while (i < a.length) { grape += a[i]; i++; } return grape; } public static void main (String[] args) { int[] a = new int[10]; // put values into the array System.out.println ("max = " + max2(a)); } Hey, look! The parameter to main makes sense, finally! Quiz ---- Different kinds of traversals: ACCUMULATION public static int sum (int[] a) { int i = 0; int total = 0; while (i < a.length) { total += a[i]; i++; } return total; } COUNTING public static int frequency (int[] a, int p) { int i = 0; int count = 0; while (i < a.length) { if (a[i] == p) count++; i++; } return count; } EUREKA: finding the first thing that satisfies a criterion public static int find (int[] a, int p) { int i = 0; while (i < a.length) { if (a[i] == p) return i; i++; } return -1; } EXTREME VALUE FINDING public static int max (int[] a) { int max = a[0]; int i = 1; while (i < a.length) { if (a[i] > max) max = a[i]; i++; } return max; } How to generalize these things? ------------------------------ Specify a range of indices over which to sum/count/search. This week's homework -------------------- Lots of problems where I say what to do, but not how. I will be providing hints in lecture. Work for a while, think for a while, ask questions, think for a while, repeat. This is homework 11; only one more after this one!!!