LECTURE NOTES NOVEMBER 17 2004 ASSIGNMENTS Fri 11/19 CodeLab #11 Mon 11/22 Assignment #4 ORGANIZING ARRAYS What? - organizing an array How? - (1) all non-null elements before all null elements - (2) null elements interspersed among non-null elements What? - removing an object from an array (1) How? - set that element to null What? - removing an object from an array (2) How? - (a) swap last real element and deleted element - good if unsorted - (b) move all elements over one - good if need to maintain some kind of order Exercise: - write some code to insert into ourPets - write some code to search ourPets - write some code to delete from ourPets - discuss: pros and cons of organization that we chose USING ARRAYS WITH METHODS Why? - arrays are reference variables What? - treat an array like an object with respect to methods What? - declaring an array as a parameter How? ([] ) {} ( []) {} Example? public double getMin(double[] temps) {} public boolean exists(int element, int collection[]) {} What? - passing an array as a parameter Example? int[] myInts = {5, 8, 23, 1, 4}; boolean contains23 = exists(23, myInts); What? - returning (a reference to) an array from a method How? [] () {} Example? int[] fibonacci(int numTerms) {} What? - using an array returned from a method Example? int[] fibonacci3 = fibonacci(3); for (int i = 0; i < fibonaaci3.length; i++) { System.out.println(fibonnaci3[i]); } What? - since an array is a reference, an array passed as a parameter can be modified by a method - using a method to modify an array - draw a picture Example? void incrementEach(char[] input) { for (int i = 0; i < input.length; i++) { input[i] += 1; } } public static void main( String[] args ) { char[] myName = {'M', 'i', 'c', 'h', 'e', 'l', 'l', 'e'}; incrementEach(myName); for (int i = 0; i < myName.length; i++) { System.out.print(myName[i]); } } STRETCHY ARRAYS Why? - even the user doesn't always know the size of the array - want to make arrays that automatically grow if necessary What? - stretchy arrays How? - create a class - have an add method that grows the array if there'sno more room - allocate a bigger array - typically new size is between 125% and 200% of the original size - don't want to waste too much memory - also don't want to have to grow too often - copy the data over - point the class data to the bigger array - the smaller array will automatically be cleaned up