1 / 178

Chapter 13

Chapter 13. Data Structures. 13.1 Multidimensional Arrays. Multidimensional arrays have more than one dimension. Java allows arrays to have any number of dimensions. In practice, arrays rarely have more than two dimensions. Creating and Initializing a Multidimensional Array.

blaise
Télécharger la présentation

Chapter 13

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 13 Data Structures

  2. 13.1 Multidimensional Arrays • Multidimensional arrays have more than one dimension. • Java allows arrays to have any number of dimensions. • In practice, arrays rarely have more than two dimensions.

  3. Creating and Initializing a Multidimensional Array • The declaration of a multidimensional array will contain more than one set of square brackets: int[][] a; • It’s legal to put some or all of the brackets after the array name: int[] a[]; int a[][];

  4. Creating and Initializing a Multidimensional Array • The new keyword is used to allocate space for a multidimensional array: a = new int[5][10]; a will have 5 rows and 10 columns. • The declaration of a multidimensional array can be combined with the allocation of space for the array: int[][] a = new int[5][10];

  5. Creating and Initializing a Multidimensional Array • The array a can visualized as a table with 5 rows and 10 columns:

  6. Creating and Initializing a Multidimensional Array • Rules for assigning default values to array elements: • Numbers are set to zero. • boolean elements are set to false. • Elements of a reference type are set to null. • The array a will be full of zeros initially:

  7. Creating and Initializing a Multidimensional Array • If an array declaration contains an initializer, it’s not necessary to use new to allocate space for the array. • The initializer for a two-dimensional array looks like a series of one-dimensional array initializers: int[][] square = {{8, 3, 4}, {1, 5, 9}, {6, 7, 2}}; • The square array:

  8. Subscripting a Multidimensional Array • Selecting an element of a multidimensional array requires more than one subscript. • If a is a two-dimensional array, the element in row i, column j can be accessed by writing a[i][j] • Each subscript can be a literal, a variable, or any expression that produces an int value. • Java requires square brackets around each subscript: writing a[i,j] would be illegal.

  9. Processing the Elements in a Multidimensional Array • The elements of a multidimensional array can be accessed sequentially or in no particular order. • For a two-dimensional array, sequential access is normally done by visiting all elements in row 0, then all elements in row 1, and so on. • It’s also possible to visit elements column by column.

  10. Processing the Elements in a Multidimensional Array • Statements that sum the elements in an array a by visiting the elements row by row: int sum = 0; for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) sum += a[row][col]; • Because the loops are nested, the row and col variables will take on all possible combinations of values.

  11. Processing the Elements in a Multidimensional Array • Order in which the elements of a will be visited: a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] • Nested for loops are ideal for processing multidimensional arrays.

  12. How Multidimensional Arrays Are Stored • In Java, a two-dimensional array is a one-dimensional array whose elements are one-dimensional arrays. • Let a be the following array: int[][] a = new int[5][10]; • How a is stored:

  13. How Multidimensional Arrays Are Stored • Because a is really a one-dimensional array, it’s legal to write a.length to find the number of rows in a. • The expression a[0].length gives the number of columns. (The choice of 0 is arbitrary.) • The length of the next dimension—if a had more than two dimensions—would be a[0][0].length, and so on.

  14. How Multidimensional Arrays Are Stored • An improved version of the code that uses nested loops to sum the elements of a two-dimensional array: for (int row = 0; row < a.length; row++) for (int col = 0; col < a[0].length; col++) sum += a[row][col]; • The literals representing the number of rows and columns have been replaced by a.length and a[0].length.

  15. Using Two-Dimensional Arrays as Matrices • Multidimensional arrays play an important role in mathematical calculations, because a matrix can be stored in a two-dimensional array. • Two example matrices:

  16. Using Two-Dimensional Arrays as Matrices • A and B can be represented by two-dimensional arrays: double[][] a = new double[2][3]; double[][] b = new double[3][2]; • The subscripts will be off by 1, however, as they were for vectors. • For example, element aij of the matrix A will be stored in element a[i-1][j-1] of the array a.

  17. Using Two-Dimensional Arrays as Matrices • Common operations on matrices include addition, subtraction, and multiplication. • Formula for computing the product of A and B: • In general, A and B can be multiplied only if the number of columns in A matches the number of rows in B.

  18. Using Two-Dimensional Arrays as Matrices • Statements that multiply arrays named a and b, storing the result in a new array named c: double[][] c = new double[a.length][b[0].length]; for (int row = 0; row < a.length; row++) for (int col = 0; col < b[0].length; col++) { c[row][col] = 0.0; for (int i = 0; i < b.length; i++) c[row][col] += a[row][i] * b[i][col]; } The number of columns in a must be equal to the number of rows in b.

  19. Using Two-DimensionalArrays to Store Images • Two-dimensional arrays are often used to store images. • Images are sometimes stored in gray scale, rather than in color. • In a gray-scale image, each pixel is a shade of gray. • Typically there are 256 shades, represented by integers between 0 (black) and 255 (white).

  20. Using Two-DimensionalArrays to Store Images • A sample gray-scale image:

  21. Using Two-DimensionalArrays to Store Images • A two-dimensional array of integers that represents this image:

  22. Using Two-DimensionalArrays to Store Images • Ways to store a full-color image: • Three parallel two-dimensional arrays (storing the red, green, and blue components of the pixels) • A two-dimensional array of Color objects • A three-dimensional array

  23. Using Two-DimensionalArrays to Store Images • A three-dimensional array that could be used to store a full-color image: int[][][] colorImage = new int[numRows][numColumns][3]; • The pixel at position (row,column) would be represented by three array elements: colorImage[row][column][0] — red component colorImage[row][column][1] — green component colorImage[row][column][2] — blue component

  24. Using Two-DimensionalArrays to Store Images • Arrays often occupy large amounts of memory, especially when they have more than one dimension. • If numRows and numColumns are both 1000, the colorImage array will require 12,000,000 bytes of memory (1000  1000  3  4). • Arrays this large may exceed the limits of a Java interpreter.

  25. Using Two-DimensionalArrays to Store Images • Memory can often be conserved by switching to a smaller element type (short instead of int or float instead of double). • Switching from int to short will reduce the colorImage array’s memory requirements by a factor of 2.

  26. Using Two-DimensionalArrays to Store Images • Storing colors as byte values is possible, even though byte values range from –128 to 127 instead of 0 to 255. • By subtracting 128 from each color value when storing it into the array, color values can be scaled so that they become legal byte values. • Switching to byte will reduce the size of the colorImage array by a factor of 4.

  27. Ragged Arrays • Each row of a two-dimensional array is an array in its own right, so there’s no reason that the rows can’t have different lengths. • If they do, the array is said to be ragged. • A table containing distances between major American cities:

  28. Ragged Arrays • The table could be stored as a two-dimensional array with eight rows and eight columns, using a total of 64 elements. • However, it’s possible to save space by using a ragged array instead. • The elements on the diagonal aren’t used, so there’s no need to store them. • The values above the diagonal are symmetric to the values below the diagonal, so it’s not necessary to store both groups.

  29. Ragged Arrays • If a ragged array is initialized at the time the array is declared, the rows in the initializer can have different lengths. • A declaration that creates and initializes an array containing the distances between cities: int[][] distances = {null, {1110}, { 710, 1000}, { 790, 1830, 1090}, {2190, 3020, 2050, 1540}, { 850, 210, 810, 1610, 2790}, {2480, 3130, 2170, 1910, 390, 2930}, { 620, 450, 710, 1370, 2650, 240, 2840}};

  30. Ragged Arrays • There’s no need to store the first row of the table. • However, the array will be easier to work with if it has eight rows, corresponding to the eight cities. • Putting null at the beginning of the array indicates that row 0 has no elements.

  31. Ragged Arrays • The appearance of the distances array:

  32. Ragged Arrays • Creating a ragged array without initializing it is a little more difficult. • Steps needed to allocate space for the distances array without initializing it: • Create a one-dimensional array with eight elements, which will be arrays of integers. • Use a loop to allocate storage for each of the “inner” arrays.

  33. Ragged Arrays • Statements that perform both steps: int[][] distances = new int[8][]; for (int i = 1; i < distances.length; i++) distances[i] = new int[i]; • The value of distances[0] will be null by default. • The length of a row can be changed during program execution. • Each row is a separate one-dimensional array, so it can be replaced by another one-dimensional array of a different length.

  34. Using Multidimensional Arrays as Parameters and Results • Multidimensional arrays can be passed to methods and returned by methods. • A method that returns the sum of all the elements in the two-dimensional array a: public static int sumElements(int[][] a) { int total = 0; for (int row = 0; row < a.length; row++) for (int col = 0; col < a[row].length; col++) total += a[row][col]; return total; } • Using a[row].length as the limit on the inner loop allows the array to have rows of different lengths.

  35. Using Multidimensional Arrays as Parameters and Results • Methods that return multidimensional arrays are not uncommon in Java. • A method that returns an identity matrix of a specified rank: public static double[][] createIdentityMatrix(int rank) { double[][] matrix = new double[rank][rank]; for (int row = 0; row < rank; row++) for (int col = 0; col < rank; col++) if (row == col) matrix[row][col] = 1.0; return matrix; }

  36. Using Multidimensional Arrays as Parameters and Results • To save time, createIdentityMatrix assigns values only to elements on the main diagonal of matrix. • Other elements will have the value 0.0 by default. • A sample call: double[][] identityMatrix = createIdentityMatrix(3);

  37. Program: Finding the DistanceBetween Two Cities • The FindDistance program will display the distance between two cities: This program finds the distance between two cities. Supported cities: Atlanta, Boston, Chicago, Houston, Los Angeles, New York, San Francisco, Washington. Enter starting city: San Francisco Enter destination city: Atlanta The distance from San Francisco to Atlanta is 2480 miles. • The user will be asked to re-enter the name of a city if it doesn’t match any of the names supported by the program. • A normal two-dimensional array will be used to store the distances between cities. A ragged array could be used instead.

  38. FindDistance.java // Finds the distance between two major American cities import jpb.*; public class FindDistance { private static final String[] CITY_NAMES = {"Atlanta", "Boston", "Chicago", "Houston", "Los Angeles", "New York", "San Francisco", "Washington"}; private static final int[][] DISTANCES = {{ 0, 1110, 710, 790, 2190, 850, 2480, 620}, {1110, 0, 1000, 1830, 3020, 210, 3130, 450}, { 710, 1000, 0, 1090, 2050, 810, 2170, 710}, { 790, 1830, 1090, 0, 1540, 1610, 1910, 1370}, {2190, 3020, 2050, 1540, 0, 2790, 390, 2650}, { 850, 210, 810, 1610, 2790, 0, 2930, 240}, {2480, 3130, 2170, 1910, 390, 2930, 0, 2840}, { 620, 450, 710, 1370, 2650, 240, 2840, 0}};

  39. public static void main(String[] args) { // Display initial message, including a list of legal // cities System.out.println( "This program finds the distance between two cities.\n" + "Supported cities: Atlanta, Boston, Chicago, Houston,\n" + "Los Angeles, New York, San Francisco, Washington.\n"); // Call getCityCode to obtain codes for starting city // and destination city int start = getCityCode("Enter starting city: "); int destination = getCityCode("Enter destination city: "); // Display distance between chosen cities System.out.println( "\nThe distance from " + CITY_NAMES[start] + " to " + CITY_NAMES[destination] + " is " + DISTANCES[start][destination] + " miles."); }

  40. // Prompts user to enter city name; returns corresponding // city code. If city name is not recognized, allows user // to enter another name. private static int getCityCode(String prompt) { while (true) { SimpleIO.prompt(prompt); String cityName = SimpleIO.readLine().trim(); for (int i = 0; i < CITY_NAMES.length; i++) if (cityName.equalsIgnoreCase(CITY_NAMES[i])) return i; System.out.println("City name was not recognized."); } } }

  41. 13.2 The Vector Class • An array has a fixed number of elements. • The only way to enlarge an array is to allocate space for a new, larger array and then copy the values of the old array into the new one. • Vectors (instances of the Vector class) resemble arrays, except that they can grow (or perhaps shrink) during the execution of a program. • The Vector class belongs to the java.util package.

  42. Properties of Vectors • A vector stores references to objects. • There’s no limit on the number of objects that can be stored in a vector, nor is there any restriction on what type of objects can be stored. • The elements of a vector, like the elements of an array, are indexed from 0. • Key differences between vectors and arrays: • Vectors can grow or shrink as needed. • Vectors must contain objects.

  43. Properties of Vectors • Each vector has a capacity and a capacity increment. • The capacity is the number of elements the vector can store without requiring additional memory. • When a vector becomes full, Java automatically increases its capacity by the amount of the capacity increment. • The size of a vector—the number of items that it currently stores—is always less than or equal to its capacity.

  44. Properties of Vectors • A vector with a capacity of five and a size of three: Two elements of the vector are currently not in use.

  45. Creating a Vector • The Vector class has three constructors. • One of them allows the initial capacity of the vector to be specified: Vector v = new Vector(5); • The capacity of v is five and its size is zero:

  46. Storing Data into a Vector • The Vector class provides methods that add an object to a vector in one of three ways: • Add the object after all objects currently stored in the vector (addElement). • Insert the object somewhere in the middle of the vector (insertElementAt). • Replace an existing object with the new one (setElementAt). • All three methods have a parameter of type Object, representing the object to be stored.

  47. Storing Data into a Vector • Examples of calling addElement: v.addElement("a"); v.addElement("b"); v.addElement("c");

  48. Storing Data into a Vector • A call of insertElementAt: v.insertElementAt("d", 1); • insertElementAt throws an ArrayIndexOutOfBoundsException if the second argument isn’t between 0 and the vector’s size.

  49. Storing Data into a Vector • A call of setElementAt: v.setElementAt("e", 2); • ArrayIndexOutOfBoundsException is thrown if the second argument to setElementAt is out of range.

  50. Storing Data into a Vector • In a call of insertElementAt, the index at which the new element is to be inserted must be less than or equal to the vector’s current size. • In a call of setElementAt, the index at which the new element is to be stored must be less than the vector’s current size.

More Related