Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

34
Introduction to Arrays Introduction to Arrays in Java in Java Corresponds with Chapter Corresponds with Chapter 6 of textbook 6 of textbook

Transcript of Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Page 1: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Introduction to Arrays in Introduction to Arrays in JavaJava

Corresponds with Chapter 6 Corresponds with Chapter 6 of textbookof textbook

Page 2: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

What is an Array?What is an Array?Array is a data structure that represents a collection of the same types of data.

Java treats these arrays as objects. This means array variables are references, not value variable.

Individual data items in arrays are called elements.

Elements are stored consecutively (contiguously) in memory.

Each element of an array is indexed.Indexing begins at 0.

Page 3: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Introducing ArraysIntroducing ArraysArray is a data structure that represents a collection of the same types of data.

5.6

4.5

3.3

13.2

4

34.33

34

45.45

99.993

11123

double[] myList = new double[10];

myList reference myList[0]

myList[1]

myList[2]

myList[3]

myList[4]

myList[5]

myList[6]

myList[7]

myList[8]

myList[9]

Element value

Array reference variable

Array element at index 5

Page 4: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Declaring ArraysDeclaring Arrays datatype[] arrayname;datatype[] arrayname;

Example:Example:int[] myList;int[] myList;

datatype arrayname[];datatype arrayname[];

Example:Example:int myList[];int myList[];

Either syntax will work. The [] indicates that the variable being declared will be a reference to an array. Each element of the array will be a data item of the specified data type.

NOTE: declaring the array does not create it! No memory is allocated for individual array elements. This requires a separate creation step.

Page 5: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Creating ArraysCreating Arrays

arrayName = arrayName = newnew datatype[arraySize]; datatype[arraySize];

NOTE: the new keyword creates an object or array. The object or array is created in a location of memory called the heap. A reference (pointer) to the array is assigned (via =) to the variable.

Example:myList = new double[10];

Java reserved word for object

creation

Integer value indicates the number of elements

Page 6: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Declaring and CreatingDeclaring and Creatingin One Stepin One Step

datatype[] arrayname = newdatatype[] arrayname = new

datatype[arraySize];datatype[arraySize];

double[] myList = new double[10];double[] myList = new double[10];

datatype arrayname[] = newdatatype arrayname[] = new datatype[arraySize]; datatype[arraySize];

double myList[] = new double[10];double myList[] = new double[10];

NOTE: when creating an array, the value inside the square brackets [ ] indicates the size you want the array to be (i.e. the number of elements).

Page 7: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

The Length of an ArrayThe Length of an Array

Once an array is created, its size is fixed. It Once an array is created, its size is fixed. It cannot be changed. You can find its size usingcannot be changed. You can find its size using

arrayRefVar.lengtharrayRefVar.length

For example,For example,

myList.length returns 10myList.length returns 10

Page 8: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Initializing ArraysInitializing Arrays

Using a loop:Using a loop:

for (int i = 0; i < myList.length; i++)for (int i = 0; i < myList.length; i++)

myList[i] = someValue;myList[i] = someValue;

Declaring, creating, initializing in one Declaring, creating, initializing in one step:step:

double[] myList = {1.9, 2.9, 3.4, 3.5};double[] myList = {1.9, 2.9, 3.4, 3.5};

NOTE: when using an array, the value inside the square brackets [ ] indicates the index that you are looking at (i.e. the specific element).

Page 9: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Declaring, creating, Declaring, creating, initializing Using the initializing Using the Shorthand NotationShorthand Notation

double[] myList = {1.9, 2.9, 3.4, 3.5};double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent This shorthand notation is equivalent to the following statements:to the following statements:double[] myList = new double[4];double[] myList = new double[4];

myList[0] = 1.9;myList[0] = 1.9;

myList[1] = 2.9;myList[1] = 2.9;

myList[2] = 3.4;myList[2] = 3.4;

myList[3] = 3.5; myList[3] = 3.5;

Page 10: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.1 – TestArray Class

1) Declaring the reference variable

2) Creating the array

3) Assigning the array’s memory location to the reference variable

4) NOTE: TOTAL_NUMBERS is a constant with value 6

Note: new is an operator that creates an object (an array is an example of an object).

Page 11: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

How Variables are Kept in How Variables are Kept in MemoryMemory

Two categories of variablesTwo categories of variables ValueValue – contains actual data (integer, float, double, – contains actual data (integer, float, double,

boolean, or other primitive data type)boolean, or other primitive data type) ReferenceReference – contains a reference (pointer) to an object – contains a reference (pointer) to an object

or array that is located on the heap (as a result of using or array that is located on the heap (as a result of using the the newnew operator). operator).

Two different locations of memory (more to come Two different locations of memory (more to come later)later) FrameFrame StackStack – contains local variables and parameters – contains local variables and parameters

of methodsof methods HeapHeap – contains – contains objectsobjects and and arraysarrays The The newnew keyword always creates an object or array and keyword always creates an object or array and

places it in the heap.places it in the heap.

Page 12: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

HeapFrame Stack

main’sframe

args

1) Declaring the reference variable

numbers

2) Creating the array on the heap

0 1 2 3 4 5

3) Assigning the array’s memory location to the reference variable

Page 13: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.1 – TestArray Class

In a loop, read user input and insert into the array.

Note use of length property to decide when to end loop

Page 14: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Assume the user enters the numbers: 3, 2, 7, 5, 7, 1

HeapFrame Stack

main’sframe

argsnumber

s 0 1 2 3 4 5

i 0

3 2

1

7

2

5

3

7

4

1

56

Looping through the array

Note the use of the loop counter to index into the array

length is a property of array objects, indicating the number of elements

Page 15: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.1 – TestArray Class

This loop is a useful technique for finding the largest value in an array.

Note the if statement nested in the for loop.

Note the use of the loop counter to index into the array.

Page 16: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

HeapFrame Stack

main’sframe

argsnumber

s 0 1 2 3 4 5

i 1

Looping through the array

3 2 7 5 7 1

3max

3

2

7

3456

Page 17: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.1 – TestArray Class

This use of a loop with an array is similar to a linear search. More on search routines later.

Page 18: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.1 – TestArray Class

Note the concatenation of array elements to a string, again, repetitively in a loop.

Page 19: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Parallel ArraysParallel Arrays

Parallel arrays should have same length

Same index position same entity

Page 20: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Program output:

Page 21: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

MMultidimensional Arrayultidimensional ArrayssA multidimensional array is a data structure that represents a collection of the same types of data.

Java treats these arrays as objects. This means array variables are references, not value variable.

Individual data items in arrays are called elements.

Elements are stored consecutively (contiguously) in memory.

Can vary in size from two to n.

Element [0][0]Element [0][1]

Element [1][0]

Element [3][1]

Element [2][1]

Element [1][1]

Element [3][0]

Element [2][0]

Page 22: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Declaring Multidimensional Declaring Multidimensional ArraysArrays

datatype[][] arrayname;datatype[][] arrayname;

Example:Example:int[][] myList;int[][] myList;

datatype arrayname[][];datatype arrayname[][];

Example:Example:int myList[][];int myList[][];

Either syntax will work. The [][] indicates that the variable being declared will be a reference to an array. Each element of the array will be a data item of the specified data type.

NOTE: declaring the array does not create it! No memory is allocated for individual array elements. This requires a separate creation step.

Page 23: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Creating Multidimensional Creating Multidimensional ArraysArrays

arrayName = arrayName = newnew datatype[rowSize][columnSize]; datatype[rowSize][columnSize];

NOTE: the new keyword creates an object or array. The object or array is created in a location of memory called the heap. A reference (pointer) to the array is assigned (via =) to the variable.

Example: myList = new double[10][4];

Java reserved word for object

creation

Integer value indicates the number of columns

Integer value indicates the

number of rows

Page 24: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Declaring and CreatingDeclaring and Creatingin One Stepin One Step

datatype[][] arrayname = newdatatype[][] arrayname = new

datatype[rowSize][columnsize];datatype[rowSize][columnsize];

double[][] myList = new double[10][3];double[][] myList = new double[10][3];

datatype arrayname[][] = newdatatype arrayname[][] = new datatype[rowSize][columnSize]; datatype[rowSize][columnSize];

double myList[][] = new double[10][3];double myList[][] = new double[10][3];

NOTE: when creating a multidimensional array, the value inside the square brackets [ ] [ ] indicates the number of rows and columns. The total size of the array is the rows multiplied by the columns (10 * 3 = 30 elements for the example above).

Page 25: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Initializing 2-Dimensional Initializing 2-Dimensional ArraysArrays

for (int r =0; r<row; r++) { for (int c = 0; c < column; c++){ myList[r][c]=someValue; } }

double[][] myList = {double[][] myList = { {1.9, 2.9},{1.9, 2.9}, {3.4, 3.5}{3.4, 3.5}};};

NOTE: when using an array, the values inside the square brackets [] [] indicate the indexes that you are looking at (i.e. the specific element).

A 2-D array is an array of arrays

Use a nested loop to access all elements of a 2-D array, loop counters represent row and column indexes to the array.

Page 26: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Obtaining Lengths of Obtaining Lengths of Multidimensional ArraysMultidimensional Arrays

for (int r=0; r<myList.length; r++){

for (int c = 0; c<myList[r].length; c++) {

print(myList[r][c]);

}

}

NOTE: The length determines the number of elementsmyList.length determines the number of rowsmyList[r].length determines the number of elements for a given row

Page 27: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Ragged ArraysRagged Arrays

When rows in a 2-d array can vary in When rows in a 2-d array can vary in sizesize

Int [] [] myList = {Int [] [] myList = {

{1, 2, 3},{1, 2, 3},

{1, 2},{1, 2},

{1}{1}

};};

Page 28: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.12 – TotalScore Class

1) Declaring the reference variable

2) Creating the 3-d arrayd1 = student (7)d2 = exam (5)d3 = exam part (2)

3) Assigning the array’s memory location to the reference variable

Page 29: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

How Variables are Kept in How Variables are Kept in MemoryMemory

Two categories of variablesTwo categories of variables ValueValue – contains actual data (integer, float, double, – contains actual data (integer, float, double,

boolean, or other primitive data type)boolean, or other primitive data type) ReferenceReference – contains a reference (pointer) to an object – contains a reference (pointer) to an object

or array that is located on the heap (as a result of using or array that is located on the heap (as a result of using the the newnew operator). operator).

Two different locations of memory (more to come Two different locations of memory (more to come later)later) FrameFrame StackStack – contains local variables and parameters – contains local variables and parameters

of methodsof methods HeapHeap – contains – contains objectsobjects and and arraysarrays The The newnew keyword always creates an object or array and keyword always creates an object or array and

places it in the heap.places it in the heap.

Page 30: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

HeapFrame Stack

main’sframe

args

1) Declaring the reference variable

scores

3) Assigning the array’s memory location to the reference variable

20.5 22.5127.5 …

[0,0,0] [0,0,1]

[0,1,0] [0,1,1]

Note: 7 rows, 5 columns with 2 parts each for a total of 70 elements – only 4 are shown

Page 31: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Listing 6.12 – TotalScore Class

In a loop, total all of the exam parts together.

Display the total for each student.

Note:

3-D array loop nested 3-deep.

Page 32: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Page 33: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Program output:

Page 34: Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.

Contents of memory at breakpoint

Note: a 2-dimensional array is implemented as an array of arrays. Each element of the first dimension is a reference to a single dimensional array.