1CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)Lecture 18:ArraysLast time:1.switch2.break3.Case continuation (or “fall through”)4.break / continue of loopsThis lecture set:1.Intro to arrays2.Copying arrays and making arrays bigger3.Array lengths and out-of-bounds indexing4.Passing arrays and array elements to a functionCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)1Data Structures and ArraysData structures: mechanisms for storing data in a structured wayWe have seen simple data structures implemented as classes:Rational.javaRational number data stored as numerator / denominator pairArrays are a very useful data structure provided by Java and other programming languagesArray: sequence of variables of the same type homogeneous data structuresize (quantity) fixed when space is allocated orderedIndividual elements of sequence can be referenced/updated/etc.Arrays are objects (hence allocated on heap) with a reference on the stackLike other objects, “instance variables” of array = cells in array are assigned default values (0 / null / etc.) when array createdCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)2Array IndexingJava provides a special syntax for uniformly accessing cells in an arrayDeclaration of a:int[] a;Allocation of space for array named a:a = new int[5];This creates five int variables “named”::a[0],a[1],a[2],a[3],a[4]To modify contents of cell #2 to 6 and cell #1 to 74:a[2] = 6;a[1] = 74;To use the contents of cell #2 and cell #1 :System.out.println(“value = “ + (a[1]-a[2]));This access mechanism to the individual elements is called array indexingIn Java / C / C++, array cells are indexed beginning at 0 and going up to n-1 (n is number of cells)Beware: start at 0! and end at one less than the size!!2CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)3Square Brackets: [ ] and lengthThree uses in Java:Array variable declarationint[] a;Array object creationnew int[10];Array indexinga[0]array also has a.length holds the amount of space currently allocated for that arrayCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)4Alternate Declaration SyntaxTo maintain consistency with C / C++, following declaration of array variables also possibleint grade[];Compare to Java standard:int[] grade;Java standard generally preferred (“type”emphasizes array status)Alternative syntax sometimes handy:int grade[], i, gpa[];Declares two arrays of base type int: grade, gpaDeclares a single int variable: iCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)5Summary of ArraysArrays are:Sequences of cells holding values of the same type (“base type”)Objects (hence created using new)To define an array variable:int[] a; // an array with base type intTo create an array object:a = new int[10];Creates an array of 10 cellsThe base type is intTo access individual array cells: use indexinga[0], a[1], …, a[9]Cells are just like variables:They may be read: x = a[3];They may be written: a[2] = 7;3CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)6A Common Programming IdiomTo process all elements in array a…Do following:for (int i = 0; i < a.length; i++){…process the one element at a[i]…}Use fresh loop counter to avoid overwriting another variable of same name elsewhereRemember: Use i < a.length, not i <= a.lengthCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)7Copying ArraysDoes the following copy a into b?int[] a = new int[5];int[] b = a;No: a, b are aliasesHow to make a copy? For now, use loop:int[] a = new int[5];int[] b = new int[a.length];for (int i = 0; i < a.length; i++){b[i] = a[i];}CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)8Making Arrays BiggerSuppose we want to make an array bigger by adding an element.Does the following work?int[] a = new int[5];a.length++;No!We get the following:Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field array.length cannot be assignedat Sample.main(Sample.java:15)a.length is immutableNo assignment is allowed4CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)9To Make an Array Bigger…Create a new larger array objectCopy old array contents into new objectAssign address of new object to variableint[] a = new int[5];{int[] temp = new int[a.length + 1];for (int i = 0; i < a.length; i++)temp[i] = a[i];a = temp;}New variable temp created to hold copyNew block created to ensure temp does not interfere with anothervariable of the same namePrevious contents of a become garbageCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)10Arrays As ArgumentsArrays = objectsArray variables = referencesArray cells = variables of the base type (references or primitives depending on what that base type is)Both can be used as arguments to methodsArray cells: passed just like the variables of that base typeArray arguments: passed just like objectsReference to array is passed inIf the method expects an array of doubles, an array of doubles of any size can be passedPromotion does not apply. You cannot pass an intarrayCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)11Array InitializersArrays may be initialized at declaration time!int[] a = {5,0,1,2};Java:counts elements (here, 4);creates correct size of arraycopies elements into arrayreturns reference to arraySee Array Example 3HeapStacka5 0 1 25CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)12Arrays of ObjectsClass types can also be base types of arrayse.g.String[] acc = new String[3];Array cells store references to objectsArray initializers can also be usedString[] acc = {“UMD”, “UNC”, “Duke”};HeapStackaccUMDUNCDukeCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)13Arrays of Objects (continued)Class types can also be base types of arrayse.g.String[] acc = new String[3];Array cells store references to objectsArray initializers can also be usedString[] acc = {“UMD”, “UNC”, “Duke”};More complicated example than strings: Cat objectsExpressions can also appear in initializersCat[] kennel = {new Cat(“Joe”),new Cat(“Jill”),new
View Full Document