1CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)Lecture Set #15:Two-Dimensional Arrays1.2-dimensional arrays1.Ragged Arrays2.Rectangular ArraysCMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)1Recall ArraysArrays: sequences of elements from the same base typeint[] a; // array of intsDate[] d; // array of references to DatesBase type may be:Primitive (i.e. int)Reference (i.e. Date, other objects)Arrays are also objects. Notice the similarities:Arrays created using newArray elements stored on heapArray variables store references to space on the heapCMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)2Allocation of SpaceSyntax for allocating space for the 1stlevel array:char[][] a; // Array of char arraysa = new char[3][]; // Create array of 3 arraysSyntax for allocating space for the 2ndlevel of arrays:a[0] = new char[4]; // Create array of 4 chara[ 1] = new char[6]; // Create array of 6 chara[2] = new char[3]; // Create array of 3 char2CMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)3Examplechar[][] a;a = new char[3][];a[0] = new char[4];a[1] = new char[6];a[2] = new char[3];a[1][3] = ‘a’;This array has two dimensions: rows, columnsThis kind of array is called ragged because the rows are of unequal lengthHeapStackaaCMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)4Questionschar[][] a;a = new char[3][];a[0] = new char[4];a[1] = new char[6];a[2] = new char[3];What does a[1][2] = ‘x’; do?Set element in row 2, column 3 to ‘x’What does a.length return?3What does a[1].length return?6What type is a?a reference to an array of array referencesWhat Type is a[0]?a reference to an array of charactersWhat type is a[0][0]?a characterCMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)5InitializersIn one dimension:char[][] a;a = new char[3][];a[0] = {‘a’,’b’,’c’,’d’};a[1] = {‘x’,’y’,’z’};a[2] = {‘m’,’n’};In two dimensions:char[][] a = {{‘a’,’b’,’c’,’d’},{‘x’,’y’,’z’},{‘m’,’n’}};3CMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)6Rectangular ArraysOften we want 2-dimensional arrays in which rows have the same lengthTablesMatrices Java has a special short-hand syntax for creating rectangular arraysint[][] a = new int[2][4]; // 2 rows, 4 colsEquivalent to:int[][] a = new int[2][];a[0] = new int[4];a[1] = new int[4];The short-hand takes care of allocating each row, initializing each cell in each rowCMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)7Exampleint[][] a = new int[2][4];Note each cell is initialized to default value (0)Each row is a 1-dim arrayHeapStacka0 0 0 00 0 00CMSC 131 Spring 2008Jan Plane (adapted by Bonnie Dorr)82-D Arrays of Objects Also PossibleOf Strings:String[][] s = new String[4][2];s[0][0] = “Fred”;s[1][1] = “Jane”;Of Cats:Cat[][] c = new Cat[4][2];c[0][0] = new Cat(“Fred”);c[1][1] = new
View Full Document