Presentation is loading. Please wait.

Presentation is loading. Please wait.

INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 Lecture 10 Title: Arrays, Part 2 Multidimensional Arrays Reference: MalikFarrell, chap 1,

Similar presentations


Presentation on theme: "INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 Lecture 10 Title: Arrays, Part 2 Multidimensional Arrays Reference: MalikFarrell, chap 1,"— Presentation transcript:

1 INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 Lecture 10 Title: Arrays, Part 2 Multidimensional Arrays Reference: MalikFarrell, chap 1, Liang, Ch 7

2 Lecture Contents: Arrays classified Multidimensional Rectangular Arrays Multidimensional Ragged Arrays Associative Arrays

3 Predefined classes for array processing Only if not discussed in previous lesson The following predefined classes are available for Java developer’s convenience –The Arrays predefined class –The ArrayList predefined class

4 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 The Arrays predefined class The Arrays predefined class Arrays is a class used to implement arrays in Java. It is defined within java.util package and therefore needs import java.util.Arrays; command.

5 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 The Arrays predefined class Philosophy of using Arrays predefined class: F Arrays class provides a set of methods like toString(), sort(), binarySearch(), etc F The user defined array appears as an argument in a stmt that invokes Arrays’ methods int[] ar = { 10, 50, 30, 20, 70, 15 }; System.out.println(Arrays.toString(ar)); Arrays.sort(ar); System.out.println("Index of 55 is: “ + Arrays.binarySearch(ar,55)); System.out.println("Index of 30 is: “ + Arrays.binarySearch(ar,30));

6 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 The Arrays.binarySearch() Method Since binary search is frequently used in programming, Java provides several overloaded binarySearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code searches the keys in an array of numbers and an array of characters. int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println("Index is " + java.util.Arrays.binarySearch(list, 11)); char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'}; System.out.println("Index is " + java.util.Arrays.binarySearch(chars, 't')); For the binarySearch method to work, the array must be pre-sorted in increasing order. Return is 4 Return is –4 (insertion point is 3, so return is -3-1)

7 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7 The Arrays.sort() Method Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code sorts an array of numbers and an array of characters. double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars);

8 Tasks to train arrays int[] ar = { 10, 50, 30, 20, 70, 15 }; int i; System.out.println(Arrays.toString(ar)); for (i=0; i<ar.length; i++) {System.out.print(" "+ar[i]); } System.out.println(); Arrays.sort(ar); for (i=0; i<ar.length; i++) {System.out.print(" "+ar[i]); } System.out.println(); System.out.println(Arrays.toString(ar)); System.out.println("Index of value 55 is: “ + Arrays.binarySearch(ar,55)); System.out.println("Index of value 30 is: “ + Arrays.binarySearch(ar,30));

9 The ArrayList predefined class The ArrayList predefined class The ArrayList class implements an array as a list. Its size may change dynamically. In order to use this class, import java.util.ArrayList; command is must.

10 The ArrayList predefined class Philosophy of using Arraylist predefined class: Before all an object of the ArrayList class must be created as an empty array. ArrayList ar = new ArrayList();. Arraylist class provides a set of methods like add(), remove(), get(), toString() etc see next slide. The add() and remove() methods serve to add and remove array elements Any ArrayList method gets invoked as a method of the user defined array in the following context: ar.add("Varna"); ar.add("Bourgas"); ar.add("Plovdiv"); ar.remove("Sofia");

11 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11 The ArrayList Class You can create an array to store objects. But the array’s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects.

12 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 Generic Type ArrayList is known as a generic class with a generic type E. You can specify a concrete type to replace E when creating an ArrayList. For example, the following statement creates an ArrayList and assigns its reference to variable cities. This ArrayList object can be used to store strings. TestArrayListRun ArrayList cities = new ArrayList ();

13 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13 Differences and Similarities between Arrays and ArrayList DistinctNumbersRun

14 Tasks to train arrays package sbarraylist; import java.util.ArrayList; public class SBArrayList { public static void main(String[] args) { ArrayList ar = new ArrayList(); ar.add("Sofia"); ar.add("Varna"); ar.add("Bourgas"); ar.add("Plovdiv"); System.out.println(ar.toString()); for (int i=ar.size()-1; i>=0; i--) System.out.print(ar.get(i) + " "); }

15 Arrays Classified Static Arrays Dynamic Arrays Stack-Based and Heap-Based Arrays Single-Dimensional Arrays Multi-Dimensional Rectangular Arrays Multi-Dimensional Ragged Arrays Associative Arrays

16 Static Arrays Тerm “static array” is used in two different contexts: Arrays with size defined at compile time. Arrays qualified static when declared (storage class: static in C++).

17 Dynamic Arrays Term “dynamic array” is used in the following two contexts: Arrays with size to be defined or modified at run time. Arrays, implemented as a list (array list).

18 Stack-Based and Heap-Based Arrays Conventional computer programs are structured to include a code segment and a data segment. Data may be allocated in two alternate memory areas – the stack and the heap. Value types in Java occupy the stack. Arrays in Java are reference types. They are dynamically allocated, occupy the heap and access to them is by an array reference variable.

19 Single-Dimensional Arrays Already discussed in details

20 Multidimensional Rectangular arrays Multidimensional Rectangular arrays

21 Multidimensional Rectangular arrays These arrays have more than one dimension. There are two approaches to interpret and implement multidimensional arrays: matrix-style multidimensional arrays; array of arrays style. With matrix style, two-dimensional arrays are considered as a table or a matrix. A rule dictates that the first/left-most/ dimension means the number of array rows and the second dimension is for the number of array columns, and so on in case of more dimensions. Two-dimensional arrays suppose consecutive element location which may implement by columns or by rows. The address value to access individual elements gets computed as an offset to the base address using one of following formulas (N-number of row, M-number of column): Allocation by columns: Address/Offset(A[i,j]) = (j - 1) * N + i Allocation by rows: Address/Offset(A[i,j]) = (i - 1) * M + j

22 Multidimensional Rectangular arrays The alternate “array of arrays” style is the Java style. It means a two-dimensional array is nothing else but an array of arrays, or one-dimensional array of one- dimensional arrays or one-dimensional array of vectors or vector of vectors. Same approach may apply to arrays with more than two dimensions. A three-dimensional array is presented as a one-dimensional array of two- dimensional arrays, or as a vector of matrices.

23 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23 Motivations Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table. For example, the following table that describes the distances between the cities can be represented using a two-dimensional array.

24 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24 Declare/Create Two-dimensional Arrays // Declare array ref var dataType[][] refVar; // create anonymous array new dataType[10][10]; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType[][] refVar = new dataType[10][10]; // Alternative syntax – not recommended, forget it dataType refVar[][] = new dataType[10][10];

25 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25 Declaring Variables of Two- dimensional Arrays and Creating Two-dimensional Arrays int[][] matrix = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); double[][] x; // What is x?

26 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26 Two-dimensional Array Illustration array.length? 4 array[0].length? 3 matrix.length? 5 matrix[0].length? 5

27 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27 Declaring, Creating, and Initializing Using Shorthand Notations You can also use an array initializer to declare, create and initialize a two-dimensional array. For example, int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Same as

28 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Multidimensional arrays F To introduce a concept: Array of arrays F 2d array or matrix = 1d array of 1d arrays OK F 3d array = 1d array of 2d arrays or matrices OK F 3d array = 2d array of 1d arrays. NOT OK

29 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29 Lengths of Two-dimensional Arrays int[][] x = new int[3][4];

30 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30 Lengths of Two-dimensional Arrays, cont. int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length array[3].length array[4].length ArrayIndexOutOfBoundsException

31 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31 Processing Two-Dimensional Arrays See the examples in the text. 1. (Initializing arrays with input values) 2. (Printing arrays) 3. (Summing all elements) 4. (Summing all elements by column) 5. (Which row has the largest sum) 6. (Finding the smallest index of the largest element) 7. (Random shuffling)

32 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32 Initializing arrays with input values java.util.Scanner cin = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: "); for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = cin.nextInt(); }

33 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33 Initializing arrays with random values for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = (int)(Math.random() * 100); }

34 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34 Printing arrays for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); } System.out.println(); }

35 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35 Summing all elements int total = 0; for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { total += matrix[row][column]; }

36 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36 Summing elements by column for (int column = 0; column < matrix[0].length; column++) { int total = 0; for (int row = 0; row < matrix.length; row++) { total += matrix[row][column]; } System.out.println("Sum for column "+column+" is " + total); }

37 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37 Random shuffling for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { int i1 = (int)(Math.random() * matrix.length); int j1 = (int)(Math.random() * matrix[i].length); // Swap matrix[i][j] with matrix[i1][j1] int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1] = temp; }

38 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38 Passing Two-Dimensional Arrays to Methods PassTwoDimensionalArray Run

39 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39 Multidimensional Arrays Occasionally, you will need to represent n- dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n-dimensional arrays for n >= 3.

40 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40 Multidimensional Arrays double[][][] scores = { {{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}}, {{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}}, {{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}}, {{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}}, {{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}}, {{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}};

41 Tasks to train arrays System.out.println("\n\n2D arrays - matrix"); int[][] matrix1 = new int[3][5]; for (i=0; i<3; i++) { for (j=0; j<5; j++) { matrix1[i][j] = i*5 + j*10; } for (i=0; i<3; i++) { for (j = 0; j < 5; j++) { System.out.print(" " + matrix1[i][j]); } System.out.println(); }

42 Tasks to train arrays System.out.println("\n\n2D arrays - matrix"); // OR System.out.println(); for (i=0; i<matrix1.length; i++) { for (j = 0; j < matrix1[i].length; j++) { System.out.print(" " + matrix1[i][j]); } System.out.println(); }

43 Tasks to train arrays System.out.println("\n\n2D arrays - matrix"); // OR System.out.println(); // iteration based on data structures - for for (i=0; i<3; i++) { for (int idd : matrix1[i]) { System.out.print(" " + idd); } System.out.println(); }

44 Tasks to train arrays System.out.println("\n\n2D arrays - matrix"); // OR i=0; for (int[] id : matrix1) { for (int idd : matrix1[i]) { System.out.print(" " + idd); } i=i+1; System.out.println(); } System.out.println();

45 Tasks to train arrays // two-dimensional arrays - list of initializers System.out.println("\n2D array and list of initializers"); int[][] matrix2 = { { 51,52,53,54,55 }, { 61,62,63,64,65 }, { 71,72,73,74,75 } }; for (i=0; i<matrix2.length; i++) { for (j = 0; j < matrix2[i].length; j++) { System.out.print(" " + matrix2[i][j]); } System.out.println(); } System.out.println();

46 Multidimensional Ragged arrays Multidimensional Ragged arrays

47 Intro Processing multidimensional rectangular arrays has some drawbacks. Here is an example to illustrate them. The problem: to save in memory all month names as strings of characters. Two optional solutions are given. First solution is a two-dimensional rectangular array. We need a two- dimensional array with 12 rows as the number of months and 10 columns which is necessary to save the string with longest name, i.e. September. It’s easy to guess that after initializing the array, all rows except one have been allocated some more than needed, i.e. useless memory. This drawback may resolve using a more flexible memory location scheme. Second solution is based on the following concept. It is reasonable for each month name to allocate only the needed number of elements. The advantage is that there is no superfluous storage space and the total memory need is less than the product of twelve months and the maximum number which needs to save the month with longest name. This type of array is called a ragged array or a or jagged array.

48 Intro Problem: to save the names of all months of the year using array Solution 1: to use a rectangular table – matrix, size of 12 x 10 Solution 2: to use a more flexible data structure – ragged array or jagged array

49 2D rectangular array 2D ragged array

50 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 50 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1

51 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 51 Ragged Arrays, cont.

52 Tasks to train arrays // two-dimensional arrays - special case - Ragged array System.out.println("\n2D array - Ragged array"); int[][] matrix3 = new int[3][]; matrix3[0] = new int[] {0, 2, 4, 6, 8, 10}; matrix3[1] = new int[] {1, 3, 5, 7 }; matrix3[2] = new int[] {11, 22}; for (i=0; i<matrix3.length; i++) { System.out.println(); for (j = 0; j < matrix3[i].length; j++) { System.out.print(" " + matrix3[i][j]); } System.out.println();

53 Tasks to train arrays // two-dimensional arrays - special case - jagged array int[][] matrix4; matrix4 = new int[3][]; matrix4[0] = new int[10]; matrix4[1] = new int[ 6]; matrix4[2] = new int[ 8]; for (i=0; i<matrix4.length; i++) { System.out.println(); for (j = 0; j < matrix4[i].length; j++) { System.out.print(" " + matrix4[i][j]); } System.out.println();

54 Associative arrays import java.util.Hashtable;

55 associative arrays Associative array elements are ordered pair: /Key, Value/. The Key serves as an index to access the value of the pair. The Key may be of arbitrary type. The associative arrays size may change at run time by adding or removing array elements. Elements of associative arrays are not ordered and do not occupy consecutive memory locations. The associative arrays in Java are added as external libraries. This requires import of Java class packages. Hashtable, Map and Dictionary are synonymous terms for associative arrays.

56 Tasks to train arrays // Associative array - special case - hashtable System.out.println("\nAssociative array - key and value"); Hashtable ht=new Hashtable (); ht.put("Sofia", "BG"); ht.put("Bern", "CH"); System.out.println(" " + ht.get("Sofia")); System.out.println();

57 Tasks to train arrays // associative array - special case - hashtable System.out.println("\nAssociative array - key and value"); Hashtable htt = new Hashtable (); htt.put(new Integer(10), "BG"); htt.put(210, "DE"); System.out.println(" " + htt.get(210));

58 Thank You For Your Attention! Any Questions?


Download ppt "INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 Lecture 10 Title: Arrays, Part 2 Multidimensional Arrays Reference: MalikFarrell, chap 1,"

Similar presentations


Ads by Google