INF120 Basics in JAVA Programming
Download
1 / 58

INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 - PowerPoint PPT Presentation


  • 108 Views
  • Uploaded on

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. Lecture Contents:. Arrays classified Multidimensional Rectangular Arrays Multidimensional Ragged Arrays

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014' - vivien-kidd


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

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


Lecture contents
Lecture Contents:

  • Arrays classified

  • Multidimensional Rectangular Arrays

  • Multidimensional Ragged Arrays

  • Associative Arrays


Predefined classes for array processing
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


The arrays p r edefined class
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.


The arrays p r edefined class1
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’ 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));

5


The arrays binarysearch method
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)

6


The arrays sort method
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);


Tasks to train a rrays
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));


The arraylist p r edefined class
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.


The arraylist p r edefined class1
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");


The arraylist class
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.


Generic type
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.

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

TestArrayList

Run



Tasks to train a rrays1
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) + " ");

}

}


Arrays classified
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


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


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


Stack based and heap based arrays
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.


Single dimensional arrays
Single-Dimensional Arrays

Already discussed in details


Multidimensional rectangular arrays
MultidimensionalRectangular arrays

Multidimensional

Rectangular arrays


Multidimensional rectangular arrays1
MultidimensionalRectangular 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


Multidimensional rectangular arrays2
MultidimensionalRectangular 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.


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


Declare create two dimensional arrays
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];


Declaring variables of two dimensional arrays and creating two dimensional arrays
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?


Two dimensional array illustration
Two-dimensional Array Illustration Two-dimensional Arrays

matrix.length? 5

matrix[0].length? 5

array.length? 4

array[0].length? 3


Declaring creating and initializing using shorthand notations
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 = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9},

{10, 11, 12}

};

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;

Same as


Multidimensional arrays
Multidimensional arrays Notations

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


Lengths of two dimensional arrays
Lengths of Two-dimensional Arrays Notations

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


Lengths of two dimensional arrays cont
Lengths of Two-dimensional Arrays, cont. Notations

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


Processing two dimensional arrays
Processing Two-Dimensional Arrays Notations

See the examples in the text.

(Initializing arrays with input values)

(Printing arrays)

(Summing all elements)

(Summing all elements by column)

(Which row has the largest sum)

(Finding the smallest index of the largest element)

(Random shuffling)

31


Initializing arrays with input values
Initializing arrays with input values Notations

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

}

}

32


Initializing arrays with random values
Initializing arrays with random values Notations

for (int row = 0; row < matrix.length; row++) {

for (int column = 0; column < matrix[row].length; column++) {

matrix[row][column] = (int)(Math.random() * 100);

}

}

33


Printing arrays
Printing arrays Notations

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

}

34


Summing all elements
Summing all elements Notations

int total = 0;

for (int row = 0; row < matrix.length; row++) {

for (int column = 0; column < matrix[row].length; column++) {

total += matrix[row][column];

}

}

35


Summing elements by column
Summing elements by column Notations

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

}

36


Random shuffling
Random shuffling Notations

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;

}

}

37


Passing two dimensional arrays to methods
Passing Two-Dimensional Arrays to Methods Notations

PassTwoDimensionalArray

Run

38


Multidimensional arrays1
Multidimensional Arrays Notations

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.

39


Multidimensional arrays2
Multidimensional Arrays Notations

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

40


Tasks to train a rrays2
Tasks to train Notationsarrays

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

}


Tasks to train arrays
Tasks to train arrays Notations

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

}


Tasks to train arrays1
Tasks to train arrays Notations

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

}


Tasks to train arrays2
Tasks to train arrays Notations

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


Tasks to train arrays3
Tasks to train arrays Notations

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


Multidimensional ragged arrays
Multidimensional NotationsRagged arrays

Multidimensional

Ragged arrays


Intro
Intro Notations

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


Intro1
Intro Notations

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



Ragged arrays
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



Tasks to train arrays4
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();


Tasks to train arrays5
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();


Associative arrays
Associative arrays

Associative arrays

import java.util.Hashtable;


Associative arrays1
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.


Tasks to train arrays6
Tasks to train arrays

// Associative array - special case - hashtable

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


Tasks to train a rrays3
Tasks to train arrays

// associative array - special case - hashtable

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


Thank You

For

Your Attention!

Any Questions?


ad