58
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

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

Embed Size (px)

Citation preview

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

INF120 Basics in JAVA ProgrammingAUBG, COS dept, Spring 2014

Lecture 10Title:

Arrays, Part 2Multidimensional Arrays

Reference: MalikFarrell, chap 1, Liang, Ch 7

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

Lecture Contents:

• Arrays classified

• Multidimensional Rectangular Arrays

• Multidimensional Ragged Arrays

• Associative Arrays

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

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

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4

The Arrays predefined class

The Arrays

predefined classArrays is a class used to implement arrays in Java. It is defined within java.util package and therefore

needs import java.util.Arrays; command.

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

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: Arrays class provides a set of methods like toString(), sort(), binarySearch(), etc The user defined array appears as an argument in a stmt that invokes Arrays’ methodsint[] 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));

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6

The Arrays.binarySearch() MethodSince 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)

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7

The Arrays.sort() MethodSince 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);

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

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));

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

The ArrayList predefined class

The ArrayList

predefined classThe 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.

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

The ArrayList predefined classPhilosophy 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");

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11

The ArrayList ClassYou 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.

java.util.ArrayList<E>

+ArrayList()

+add(o: E) : void

+add(index: int, o: E) : void

+clear(): void

+contains(o: Object): boolean

+get(index: int) : E

+indexOf(o: Object) : int

+isEmpty(): boolean

+lastIndexOf(o: Object) : int

+remove(o: Object): boolean

+size(): int

+remove(index: int) : boolean

+set(index: int, o: E) : E

Creates an empty list.

Appends a new element o at the end of this list.

Adds a new element o at the specified index in this list.

Removes all the elements from this list.

Returns true if this list contains the element o.

Returns the element from this list at the specified index.

Returns the index of the first matching element in this list.

Returns true if this list contains no elements.

Returns the index of the last matching element in this list.

Removes the element o from this list.

Returns the number of elements in this list.

Removes the element at the specified index.

Sets the element at the specified index.

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

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.

TestArrayListTestArrayList RunRun

ArrayList<String> cities = new ArrayList<String>();

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13

Differences and Similarities between Arrays and ArrayList

Operation Array ArrayList

Creating an array/ArrayList String[] a = new String[10] ArrayList<String> list = new ArrayList<>();

Accessing an element a[index] list.get(index);

Updating an element a[index] = "London"; list.set(index, "London");

Returning size a.length list.size();

Adding a new element list.add("London");

Inserting a new element list.add(index, "London");

Removing an element list.remove(index);

Removing an element list.remove(Object);

Removing all elements list.clear();

DistinctNumbersDistinctNumbers RunRun

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

Tasks to train arrayspackage 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) + " "); }}

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

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

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

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++).

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

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).

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

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.

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

Single-Dimensional Arrays

• Already discussed in details

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

Multidimensional Rectangular arrays

Multidimensional

Rectangular arrays

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

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

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

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.

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23

Motivations

Chicago

Boston

New York

Atlanta

Miami

Dallas

Houston

Distance Table (in miles)

Chicago Boston New York Atlanta Miami Dallas Houston

0 983 787 714 1375 967 1087

983 0 214 1102 1763 1723 1842

787 214 0 888 1549 1548 1627

714 1102 888 0 661 781 810

1375 1763 1549 661 0 1426 1187

967 1723 1548 781 1426 0 239

1087 1842 1627 810 1187 239 0

1723 1548 781 1426 0 239

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.

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

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];

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

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?

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26

Two-dimensional Array Illustration

[0] [1] [2] [3] [4] 4

[0]

7

matrix[2][1] = 7;

matrix = new int[5][5];

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

[1] [2] [3] [4]

[0] [1] [2] [3] [4]

[0] [1] [2] [3] [4] 4 [0]

[1] [2] [3] [4]

[0] [1] [2]

7

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

1

2

3

4

5

6

8

9

10

11

12

array.length? 4

array[0].length? 3

matrix.length? 5

matrix[0].length? 5

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

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

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

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

Multidimensional arrays

To introduce a concept: Array of arrays

2d array or matrix = 1d array of 1d arrays OK

3d array = 1d array of 2d arrays or matrices OK

3d array = 2d array of 1d arrays. NOT OK

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29

Lengths of Two-dimensional Arrays

x

x[0]

x[1]

x[2]

x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3]

x.length is 3

x[0].length is 4

x[1].length is 4

x[2].length is 4

int[][] x = new int[3][4];

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

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

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

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)

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

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(); }}

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

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); }}

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

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();}

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

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]; }}

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

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);}

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

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; }}

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38

Passing Two-Dimensional Arrays to Methods

PassTwoDimensionalArrayPassTwoDimensionalArray

RunRun

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39

Multidimensional ArraysOccasionally, 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.

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40

Multidimensional Arraysdouble[][][] 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}}};

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

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(); }

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

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(); }

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

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(); }

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

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();

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

Tasks to train arrays// two-dimensional arrays - list of initializersSystem.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();

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

Multidimensional Ragged arrays

Multidimensional

Ragged arrays

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

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.

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

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

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

2D rectangular array 2D ragged array

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 50

Ragged ArraysEach 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 5matrix[0].length is 5matrix[1].length is 4matrix[2].length is 3matrix[3].length is 2matrix[4].length is 1

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

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

Ragged Arrays, cont.

1 2 3 4 5

int[][] triangleArray = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} };

2 3 4 5 3 4 5 4 5 5

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

Tasks to train arrays// two-dimensional arrays - special case - Ragged arraySystem.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();

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

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();

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

Associative arrays

Associative arrays

import java.util.Hashtable;

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

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.

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

Tasks to train arrays

// Associative array - special case - hashtableSystem.out.println("\nAssociative array - key and value"); Hashtable<String,String> ht=new Hashtable<String,String>(); ht.put("Sofia", "BG"); ht.put("Bern", "CH"); System.out.println(" " + ht.get("Sofia"));

System.out.println();

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

Tasks to train arrays// associative array - special case - hashtableSystem.out.println("\nAssociative array - key and value");

Hashtable<Integer, String> htt = new Hashtable<Integer, String>();

htt.put(new Integer(10), "BG"); htt.put(210, "DE"); System.out.println(" " + htt.get(210));

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

Thank You For

Your Attention!

Any Questions?