chapter 8 - arrays. chapter 8 common to want to deal with collection of items common to want to deal...

77
Chapter 8 - Chapter 8 - Arrays Arrays

Upload: todd-arnold

Post on 02-Jan-2016

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Chapter 8 - Chapter 8 - ArraysArrays

Page 2: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Chapter 8Chapter 8

Common to want to deal with collection of Common to want to deal with collection of itemsitems Keep information about all 302 students (250)Keep information about all 302 students (250) Information about all video files on computerInformation about all video files on computer All of my grades since kindergartenAll of my grades since kindergarten Books in a libraryBooks in a library

Infeasible to enumerate an identifier for Infeasible to enumerate an identifier for eacheach book1,book2,book3,….,book500book1,book2,book3,….,book500

Page 3: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Basic arraysBasic arrays

Arrays are a sequence of a data typeArrays are a sequence of a data type

Two componentsTwo components DatatypeDatatype SizeSize

Page 4: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

DatatypeDatatype

What type of element do we went as What type of element do we went as the base of the array?the base of the array?

Can be a primitive or reference typeCan be a primitive or reference type

Syntax:Syntax:<datatype>[] <identifier>;<datatype>[] <identifier>;

<dataype> <identifier>[];<dataype> <identifier>[];

Page 5: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

8.1 Arrays8.1 Arrays

Problem: Want to display differences Problem: Want to display differences in scores from averagein scores from average We have to keep track of each scoreWe have to keep track of each score We could just create one identifier for We could just create one identifier for

all 10 scores (score1, score2…)all 10 scores (score1, score2…) But what if we wanted to take in more But what if we wanted to take in more

scores?scores?

Solution: Use an array of scores to Solution: Use an array of scores to store all scoresstore all scoresdouble[] scores; //ORdouble[] scores; //OR

double scores[];double scores[];

Page 6: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Component 2: SizeComponent 2: Size Must use new operatorMust use new operator

Syntax:Syntax:<identifier> = new double[<size>];<identifier> = new double[<size>];

Example:Example:scores = new double[10];scores = new double[10];

double[] scores = new double[10];double[] scores = new double[10];

What data type is an array?What data type is an array?

Page 7: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Memory DiagramMemory Diagram

scorescoress

0 1 20 1 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9

Page 8: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

ArraysArrays

Can access an individual item in the Can access an individual item in the collectioncollection Use a single identifier for the whole Use a single identifier for the whole

collection (scores) and then use an collection (scores) and then use an indexed indexed expressionexpression to access an to access an array elementarray element

Zero based indexingZero based indexing

Index numbered 0 through size-1Index numbered 0 through size-1 scores[0]scores[0] scores[2]scores[2] //3//3rdrd element element

Can use expressions Can use expressions scores[i+1]scores[i+1]

Page 9: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Memory DiagramMemory Diagram

scorescoress

0 1 20 1 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9

scores[2]scores[2]

Page 10: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Output DifferenceOutput Differencedouble[] scores = new double[10];double[] scores = new double[10];

double avg, sum = 0;double avg, sum = 0;

for(int i=0; i < 10; i++){for(int i=0; i < 10; i++){

System.out.print(“Enter Score”);System.out.print(“Enter Score”);

scores[i] = in.nextDouble();scores[i] = in.nextDouble();

sum += scores[i];sum += scores[i];

}}

avg = sum/10;avg = sum/10;

for(int i=0; i < 10; i++){for(int i=0; i < 10; i++){

System.out.print("Score "+i+" ");System.out.print("Score "+i+" ");

System.out.print(score[i]+" ");System.out.print(score[i]+" ");

System.out.println(score[i] – avg);System.out.println(score[i] – avg);

}}

Page 11: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Sample RunSample Run

InputInput

Enter score: 22Enter score: 22

Enter score: 24Enter score: 24

Enter score: 90Enter score: 90

Enter score: 88Enter score: 88

Enter score: 75Enter score: 75

Enter score: 95Enter score: 95

Enter score: 65Enter score: 65

Enter score: 80Enter score: 80

Enter score: 92Enter score: 92

Enter score: 69Enter score: 69

OutputOutput

Score 0 22.0 -48.0Score 0 22.0 -48.0

Score 1 24.0 -46.0Score 1 24.0 -46.0

Score 2 90.0 20.0Score 2 90.0 20.0

Score 3 88.0 18.0Score 3 88.0 18.0

Score 4 75.0 5.0Score 4 75.0 5.0

Score 5 95.0 25.0Score 5 95.0 25.0

Score 6 65.0 -5.0Score 6 65.0 -5.0

Score 7 80.0 10.0Score 7 80.0 10.0

Score 8 92.0 22.0Score 8 92.0 22.0

Score 9 69.0 -1.0Score 9 69.0 -1.0

Page 12: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Initial ValuesInitial Values

When array is created, all values are When array is created, all values are initialized depending on array type: initialized depending on array type: Numbers: 0 Numbers: 0 Boolean: false Boolean: false Object References: null Object References: null

Means compiler does not force Means compiler does not force initialization like with primitivesinitialization like with primitives

Page 13: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

LengthLength

We assumed size of array was 10…what We assumed size of array was 10…what if we aren’t sure? Or want to change if we aren’t sure? Or want to change size?size?

Every array has a Every array has a public constantpublic constant data member data member length (no parenthesis)length (no parenthesis)

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

System.out.print("Score "+i+" ");System.out.print("Score "+i+" ");

System.out.print(score[i]+" ");System.out.print(score[i]+" ");

System.out.println(score[i] – avg);System.out.println(score[i] – avg);

}}

Page 14: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

InitializationInitialization Say we wanted to store all the month Say we wanted to store all the month

names?names? Can keep array of StringsCan keep array of StringsString[] monthName = new String[12];String[] monthName = new String[12];

monthName[0] = “Jan”;monthName[0] = “Jan”;

monthName[1] = “Feb”;monthName[1] = “Feb”;

monthName[2] = “Mar”;monthName[2] = “Mar”;

monthName[3] = “Apr”;monthName[3] = “Apr”;

monthName[4] = “May”;monthName[4] = “May”;

monthName[5] = “Jun”;monthName[5] = “Jun”;

monthName[6] = “Jul”;monthName[6] = “Jul”;

monthName[7] = “Aug”;monthName[7] = “Aug”;

monthName[8] = “Sep”;monthName[8] = “Sep”;

monthName[9] = “Oct”;monthName[9] = “Oct”;

monthName[10] = “Nov”;monthName[10] = “Nov”;

monthName[11] = “Dec”;monthName[11] = “Dec”;

Page 15: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Adv 8.1 Initializing Adv 8.1 Initializing arraysarrays

You can also initialize all values right You can also initialize all values right off the bat instead of individually as off the bat instead of individually as beforebefore

String[] monthName = {“Jan”, “Feb”, “Mar”, “Apr”, String[] monthName = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”}“Nov”, “Dec”}

No need to use new, or specify sizeNo need to use new, or specify size Knows size from number of values in listKnows size from number of values in list

Page 16: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Array sizesArray sizes

So far, we have used constants to So far, we have used constants to define the size of the arraydefine the size of the array Fixed-size array declarationFixed-size array declaration

What about if we aren’t sure how What about if we aren’t sure how many scores we want?many scores we want?

Solution 1 – declare array of size 100 Solution 1 – declare array of size 100 and get input until quit or 100 sizes and get input until quit or 100 sizes are inputare input

Page 17: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Array sizesArray sizes

2 problems2 problems Inefficient – wastes space (what if we get 1 Inefficient – wastes space (what if we get 1

score? Wasted space for other 99) score? Wasted space for other 99) underutilizationunderutilization

Limiting – what if we want more than 100 Limiting – what if we want more than 100 scores?scores?

Solution 2 – Solution 2 – variable size arrayvariable size array – non- – non-constant values for sizeconstant values for size But you still cannot change the size once But you still cannot change the size once

created (length is constant)created (length is constant)

Page 18: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

User defined sizeUser defined size

int size;int size;

double [] scores;double [] scores;

System.out.println("Enter number of scores to System.out.println("Enter number of scores to enter: ");enter: ");

size = in.nextInt();size = in.nextInt();

scores = new double[size];scores = new double[size];

Can use any mathematic expressionCan use any mathematic expression Must give a whole number (integer)Must give a whole number (integer)

Page 19: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Array of ObjectsArray of Objects

BankAccount[] ba;BankAccount[] ba;

System.out.print(“Enter number of accounts: “);System.out.print(“Enter number of accounts: “);

int numAccounts = in.nextInt();int numAccounts = in.nextInt();

ba = new BankAccount[numAccounts];ba = new BankAccount[numAccounts];

ba[0].deposit(500);ba[0].deposit(500);

What’s wrong?What’s wrong?

Page 20: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Objects and arraysObjects and arrays

We have created the array(i.e. the We have created the array(i.e. the bins)bins)

What’s in the bins?What’s in the bins?

We still need to create an object for We still need to create an object for each bineach bin

Page 21: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Memory DiagramMemory Diagram

baba

0 1 20 1 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 ……

Page 22: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Create objectsCreate objects

Each “bin” (index of the array) is a Each “bin” (index of the array) is a referencereference

When we declare an array, we declare When we declare an array, we declare numAccountsnumAccounts identifiers in essence identifiers in essence

Now we need to create a BankAccount Now we need to create a BankAccount object for each binobject for each bin

Page 23: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Array of ObjectsArray of ObjectsBankAccount[] ba;BankAccount[] ba;

System.out.print(“Enter number of accounts: “);System.out.print(“Enter number of accounts: “);

int numAccounts = in.nextInt();int numAccounts = in.nextInt();

ba = new BankAccount[numAccounts];ba = new BankAccount[numAccounts];

ba[0] = new BankAccount();ba[0] = new BankAccount();

ba[0].deposit(500);ba[0].deposit(500);

Page 24: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Memory DiagramMemory Diagram

baba

0 1 20 1 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 ……

:BankAccou:BankAccountnt

505000

balancbalancee

Page 25: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Arrays of ObjectsArrays of Objects

We will use the We will use the PersonPerson class to class to illustrate this concept.illustrate this concept.

An array of objects is declared and An array of objects is declared and created just as an array of primitive created just as an array of primitive data types is.data types is.Person[] person;Person[] person;

person = new Person[20];person = new Person[20];

Page 26: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Fig. 10.4 WuFig. 10.4 Wu

An array of An array of PersonPerson objects after the objects after the array is created.array is created.

Page 27: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

The person array with one The person array with one Person Person object added to it.object added to it.

Page 28: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Arrays of ObjectsArrays of Objects

To assign data values to this object, we To assign data values to this object, we can executecan execute

person[0].setName (“Ms. Latte”);person[0].setName (“Ms. Latte”);

person[0].setAge (20);person[0].setAge (20);

person[0].setGender (‘F’);person[0].setGender (‘F’);

The syntax here is the one used to call an The syntax here is the one used to call an object’s method; we are using an indexed object’s method; we are using an indexed expression to refer to the object instead expression to refer to the object instead of a simple variable.of a simple variable.

Page 29: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

The following program illustrates The following program illustrates various aspects of array processing:various aspects of array processing: Creating a new person array.Creating a new person array. Creating a new Person object and assigning Creating a new Person object and assigning

values to it.values to it. Finding the average age of the persons in the Finding the average age of the persons in the

array.array. Finding the youngest and oldest persons in the Finding the youngest and oldest persons in the

array.array. Finding a particular person in the array.Finding a particular person in the array.

Page 30: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

/*/*Chapter 10 Sample Program: Illustrate the processing Chapter 10 Sample Program: Illustrate the processing

of an array of Person objectsof an array of Person objects

File: Ch10ProcessPersonArray.javaFile: Ch10ProcessPersonArray.java*/*/

class Ch10ProcessPersonArray {class Ch10ProcessPersonArray {

public static void main (String[] args) {public static void main (String[] args) {

Person[] person; //declare the person arrayPerson[] person; //declare the person array person = new Person[5]; //and then create itperson = new Person[5]; //and then create it

Page 31: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

//----------- Create person Array ------------////----------- Create person Array ------------// String name, inpStr;String name, inpStr; int age;int age; char gender;char gender;

for (int i = 0; i < person.length; i++) {for (int i = 0; i < person.length; i++) { //read in data values//read in data values

System.out.println(“Enter info for a person”);System.out.println(“Enter info for a person”);

name = in.nextLine();name = in.nextLine(); age = in.nextInt();age = in.nextInt(); inpStr = in.next().charAt(0); inpStr = in.next().charAt(0);

//create a new Person and assign values//create a new Person and assign values person[i] = new Person( );person[i] = new Person( );

person[i].setName ( name );person[i].setName ( name ); person[i].setAge ( age );person[i].setAge ( age ); person[i].setGender( gender );person[i].setGender( gender );}}

Page 32: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

//------ Compute Average Age --------------////------ Compute Average Age --------------// float sum = 0, averageAge;float sum = 0, averageAge; for (int i = 0; i < person.length; i++) {for (int i = 0; i < person.length; i++) { sum += person[i].getAge();sum += person[i].getAge(); }}

averageAge = sum / (float) person.length;averageAge = sum / (float) person.length;

System.out.println("Average age: " + System.out.println("Average age: " + averageAge);averageAge);

//-- Find the youngest and oldest person ------////-- Find the youngest and oldest person ------//

Person youngest, //points to the youngest personPerson youngest, //points to the youngest person oldest; //points to the oldest personoldest; //points to the oldest person

youngest = person[0];youngest = person[0]; oldest = person[0];oldest = person[0];

Page 33: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

for (int i = 1; i < person.length; i++) {for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) {if ( person[i].getAge() < youngest.getAge() ) { //found a younger person//found a younger person youngest = person[i];youngest = person[i]; }} else if (person[i].getAge() > oldest.getAge() ) {else if (person[i].getAge() > oldest.getAge() ) { //found an older person//found an older person oldest = person[i];oldest = person[i]; }}}}System.out.println("Oldest: " + oldest.getName()System.out.println("Oldest: " + oldest.getName() + " is " + oldest.getAge() + " years old.");+ " is " + oldest.getAge() + " years old.");

System.out.println("Youngest: " + System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getName() + " is " + youngest.getAge() youngest.getAge() + " years old.");+ " years old.");

Page 34: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Fig. 10.6Fig. 10.6 An array of An array of PersonPerson objects with two objects with two

PersonPerson variables. variables.

Page 35: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Deleting objectDeleting object

How do we delete an object?How do we delete an object?

tms[x] = null;tms[x] = null;

Remember Remember garbage collectiongarbage collection takes any objects no longer being takes any objects no longer being referenced to (i.e. can never be referenced to (i.e. can never be accessed again)accessed again)

Page 36: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

8.3 Wrappers8.3 Wrappers

Page 37: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Wrapper classesWrapper classes

Allow us to treat primitives as Allow us to treat primitives as objectsobjects

Each wrapper class has a primitive Each wrapper class has a primitive data memberdata member

Page 38: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all
Page 39: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

8.4 Enhanced 8.4 Enhanced forfor Loop Loop

The traditional for loop – The traditional for loop – iteratingiterating through arraysthrough arrays

double[] data = . . .;double[] data = . . .;double sum = 0;double sum = 0;for (int i = 0; i < data.length; i++)for (int i = 0; i < data.length; i++){{

double e = data[i];double e = data[i];sum = sum + e;sum = sum + e;

}}

Page 40: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

8.5 Simple Array 8.5 Simple Array MethodsMethods

Finding AverageFinding Average

double[] scores = ...//Get scores from userdouble[] scores = ...//Get scores from user

double avg = 0;double avg = 0;

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

avg += scores[i];avg += scores[i];

}}

avg = avg / scores.length;avg = avg / scores.length;

Page 41: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

CountCountdouble[] scores = ...//Get scores from userdouble[] scores = ...//Get scores from user

double avg = 0;double avg = 0;for(int i = 0; i < scores.length; i++){for(int i = 0; i < scores.length; i++){

avg += scores[i];avg += scores[i];}}avg = avg / scores.length;avg = avg / scores.length;

int count = 0;int count = 0;for(int i = 0; i < scores.length; i++){ for(int i = 0; i < scores.length; i++){

if(scores[i] >= avg){if(scores[i] >= avg){count++;count++;

}}}}

Page 42: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Find ValueFind Value

double[] scores = ...//Get scores from filedouble[] scores = ...//Get scores from file

double search = ...//Get value to search from userdouble search = ...//Get value to search from user

boolean found = false;boolean found = false;

for(int j = 0; j < scores.length; j++)for(int j = 0; j < scores.length; j++)

{{

if(Math.abs(scores[j],search) <= 1E-14)if(Math.abs(scores[j],search) <= 1E-14)

{{

found = true;found = true;

}}

}}

Page 43: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Maximum/MinimumMaximum/Minimumdouble max = scores[0];double max = scores[0];

double min = scores[0];double min = scores[0];

for(int i = 1; i < scores.length; i++)for(int i = 1; i < scores.length; i++)

{{

if(scores[i] > max)if(scores[i] > max)

{{

max = scores[i];max = scores[i];

}}

else if(scores[i] < min)else if(scores[i] < min)

{{

min = scores[i];min = scores[i];

}}

}}

Page 44: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

For ObjectsFor Objectspublic class Bankpublic class Bank{{

public int count(double atLeast)public int count(double atLeast){{

int matches = 0;int matches = 0;for (int j = 0; j < accounts.length; j+for (int j = 0; j < accounts.length; j+

+)+){{ if (accounts[j].getBalance() >= if (accounts[j].getBalance() >=

atLeast) atLeast) matches++;matches++;

// Found a match// Found a match}}return matches;return matches;

}}. . .. . .private BankAccount[] accounts;private BankAccount[] accounts;

} }

Page 45: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

For ObjectsFor Objectspublic class Bankpublic class Bank{{

public BankAccount find(int accountNumber)public BankAccount find(int accountNumber){{

for (int j = 0; j < accounts.length; j++)for (int j = 0; j < accounts.length; j++){{

if (accounts[j].getAccountNumber() == if (accounts[j].getAccountNumber() == accountNumber) // Found a matchaccountNumber) // Found a match

return accounts[j];return accounts[j];}}return null; // No match in the array listreturn null; // No match in the array list

}}} }

Page 46: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

For ObjectsFor Objects

public BankAccount maximum()public BankAccount maximum(){{

if (accounts.length == 0) return null;if (accounts.length == 0) return null; BankAccount largestYet = accounts[0];BankAccount largestYet = accounts[0];for (int i = 1; i < accounts.length; i++)for (int i = 1; i < accounts.length; i++){{

BankAccount a = accounts[i];BankAccount a = accounts[i];if (a.getBalance() > largestYet.getBalance())if (a.getBalance() > largestYet.getBalance())

largestYet = a;largestYet = a;}}return largestYet;return largestYet;

} }

Page 47: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

10.5 Dimensional Arrays10.5 Dimensional Arrays

So far: Only one dimensional arraysSo far: Only one dimensional arrays

Many problems may require us to Many problems may require us to represent data in a “table” format, represent data in a “table” format, or along two-dimensionsor along two-dimensions Two-dimensional arraysTwo-dimensional arrays

What do we need to add?What do we need to add?

Page 48: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

2D Arrays2D Arrays

Two indices – x and yTwo indices – x and y

Example:Example: We have multiple students, and each We have multiple students, and each

student has multiple scores – row for student has multiple scores – row for student, column for teststudent, column for test

int[][] scores;int[][] scores;

scores = new int[numStudents][numTests];scores = new int[numStudents][numTests];

Page 49: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

10.5 Two-Dimensional 10.5 Two-Dimensional ArraysArrays

To declare our example array, we state:To declare our example array, we state:

double[][] payScaleTable;double[][] payScaleTable;

or or double payScaleTable[][];double payScaleTable[][];

and create the array asand create the array as

payScaleTable = new double[4][5];payScaleTable = new double[4][5];

Page 50: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Fig. 10.16 WuFig. 10.16 Wu Accessing an element of a two-Accessing an element of a two-

dimensional array.dimensional array.

Page 51: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

2D Arrays2D Arrays

Arrays are a specific structureArrays are a specific structure

Two dimensional arrays are notTwo dimensional arrays are not They are an array of arraysThey are an array of arrays

How do you check number of rows? How do you check number of rows? Columns? (using the length member)Columns? (using the length member)

Page 52: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

10.5 Two-Dimensional 10.5 Two-Dimensional ArraysArrays

The sample array creationThe sample array creationpayScaleTable = new double[4][5];payScaleTable = new double[4][5];

is a shorthand foris a shorthand forpayScaleTable = new double [4][ ];payScaleTable = new double [4][ ];

payScaleTable[0] = new double [5];payScaleTable[0] = new double [5];

payScaleTable[1] = new double [5];payScaleTable[1] = new double [5];

payScaleTable[2] = new double [5];payScaleTable[2] = new double [5];

and so on.and so on.

Page 53: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Fig. 10.17A WuFig. 10.17A Wu Executing the statements on the left Executing the statements on the left

in sequence will create the array of in sequence will create the array of arrays shown on the right.arrays shown on the right.

Page 54: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all
Page 55: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

10.5 Two-Dimensional 10.5 Two-Dimensional ArraysArrays

The expressionThe expressionpayScaleTable.lengthpayScaleTable.length

refers to the length of the refers to the length of the payScaleTablepayScaleTable array itself. array itself.

Page 56: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

10.5 Two-Dimensional 10.5 Two-Dimensional ArraysArrays The expressionThe expression

payScaleTable[1].lengthpayScaleTable[1].length

refers to the length of the array refers to the length of the array stored at row 1 of stored at row 1 of payScaleTablepayScaleTable..

Page 57: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

How do you “traverse”, or go through How do you “traverse”, or go through the elements of an multidimensional the elements of an multidimensional array?array? Row-major order (first row first, etc)Row-major order (first row first, etc) Column-major order (first column first, etc)Column-major order (first column first, etc)

We can make higher-dimensional arrays We can make higher-dimensional arrays (3, 4, or more) the same way we make (3, 4, or more) the same way we make 2D arrays2D arrays

Page 58: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

8.7 Copying Arrays8.7 Copying Arrays

Arrays are reference variables, treat Arrays are reference variables, treat like other objectslike other objects

Copying an array variable yields a Copying an array variable yields a second reference to the same arraysecond reference to the same array

double[] data = new double[10];double[] data = new double[10];// fill array . . .// fill array . . .double[] prices = data; double[] prices = data;

Page 59: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all
Page 60: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

CloneClone

Use clone to make true copyUse clone to make true copy

double[] prices = (double[]) data.clone(); double[] prices = (double[]) data.clone();

//Note clone returns an object, so we //Note clone returns an object, so we type type // cast// cast

Page 61: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all
Page 62: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Copying ElementsCopying Elements

System.arraycopy() not encouragedSystem.arraycopy() not encouraged Hard to manipulateHard to manipulate Using for loops is more powerfulUsing for loops is more powerful

Page 63: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Copying Copying certain certain

elementselementsHow do I copy How do I copy countcount

positions from positions from array array fromfrom to array to array toto, starting at , starting at positions positions fromStartfromStart and and toStarttoStart respectively?respectively?

Page 64: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Common use: insertCommon use: insert//insert x in position i of newData//insert x in position i of newData

//we already have an array called //we already have an array called

int newData = new int[data.length+1];int newData = new int[data.length+1];

//<loop to copy elements before i>//<loop to copy elements before i>

//insert the new element//insert the new element

newData[i] = x; newData[i] = x;

//<loop to copy elements after i>//<loop to copy elements after i>

data = newData;data = newData;

Page 65: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Common use: insertCommon use: insert//insert x in position i of newData//insert x in position i of newData

//we already have an array called //we already have an array called

int newData = new int[data.length+1];int newData = new int[data.length+1];

//<loop to copy elements before i>//<loop to copy elements before i>

for (int pos=0; pos<i; pos++)for (int pos=0; pos<i; pos++)

newData[pos] = data[pos];newData[pos] = data[pos];

//insert the new element//insert the new element

newData[i] = x; newData[i] = x;

//<loop to copy elements after i>//<loop to copy elements after i>

data = newData;data = newData;

Page 66: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Common use: insertCommon use: insert//insert x in position i of newData//insert x in position i of newData//we already have an array called //we already have an array called int newData = new int[data.length+1];int newData = new int[data.length+1];

//<loop to copy elements before i>//<loop to copy elements before i>for (int pos=0; pos<i; pos++)for (int pos=0; pos<i; pos++)

newData[pos] = data[pos];newData[pos] = data[pos];

//insert the new element//insert the new elementnewData[i] = x; newData[i] = x;

//<loop to copy elements after i>//<loop to copy elements after i>for (int pos=i+1; pos<newData.length; pos++)for (int pos=i+1; pos<newData.length; pos++)

newData[pos] = data[pos-1];newData[pos] = data[pos-1];

data = newData;data = newData;

Page 67: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Growing arrayGrowing array If the array is full and you need more If the array is full and you need more

space, you can grow the arrayspace, you can grow the array

Create a new, larger array. Create a new, larger array. double[] newData = new double[2 * data.length];double[] newData = new double[2 * data.length];

Copy all elements into the new array Copy all elements into the new array

Store the reference to the new array in Store the reference to the new array in the array variable the array variable data = newData;data = newData;

Page 68: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all
Page 69: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Passing Arrays to Passing Arrays to MethodsMethods

Exactly the same as objects, the Exactly the same as objects, the referencereference is passed to method is passed to method parametersparameters And for returning an objectAnd for returning an object

lengthlength is especially important in is especially important in methods, since we have no other way methods, since we have no other way of knowing the size(except sending of knowing the size(except sending another parameter)another parameter)

Page 70: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Passing Arrays to MethodsPassing Arrays to Methodspublic int searchMinimum(double[] number) {public int searchMinimum(double[] number) {

int indexOfMinimum = 0;int indexOfMinimum = 0;

for (int i = 1; i < number.length; i++){for (int i = 1; i < number.length; i++){ if (number[i] < number[indexOfMinimum]) { if (number[i] < number[indexOfMinimum]) { //found a smaller element//found a smaller element

indexOfMinimum = i;indexOfMinimum = i; }}

}}return indexOfMinimum;return indexOfMinimum;

}}

To call this method (from a method of the same To call this method (from a method of the same class), we writeclass), we write

Page 71: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Passing Arrays to MethodsPassing Arrays to Methodsdouble[] arrayOne;double[] arrayOne;

//create and assign values to arrayOne//create and assign values to arrayOne

......

//get the index of the smallest element of arrayOne//get the index of the smallest element of arrayOne

int minOne = searchMinimum(arrayOne);int minOne = searchMinimum(arrayOne);

//output the result//output the result

System.out.print(“Minimum value in Array One is ”);System.out.print(“Minimum value in Array One is ”);

System.out.print(arrayOne[minOne] + “at position ” System.out.print(arrayOne[minOne] + “at position ” + minOne);+ minOne);

......

Page 72: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Fig. 10.9B WuFig. 10.9B Wu Passing an array to a method Passing an array to a method

means we are passing a means we are passing a reference to an array.reference to an array.

Page 73: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

Adv 8.4 Partially Filled Adv 8.4 Partially Filled ArraysArrays

Use partially filled arrays to deal with Use partially filled arrays to deal with sets where size is not known before sets where size is not known before handhand MUST keep track of capacity and size to MUST keep track of capacity and size to

ensure array does not get overfilledensure array does not get overfilled

Make size largeMake size large Either resize array or enforce a limit Either resize array or enforce a limit

when fullwhen full

Page 74: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

int capacity = 100;int capacity = 100;

double[] data = new double[capacity];double[] data = new double[capacity];

int dataSize = 0;int dataSize = 0;

boolean stop = false;boolean stop = false;

while(!stop)while(!stop)

{{

System.out.print(“Enter data: “);System.out.print(“Enter data: “);if(in.hasNextDouble())if(in.hasNextDouble())

{{

double x = in.nextDouble();double x = in.nextDouble();

Page 75: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

if(dataSize >= capacity)if(dataSize >= capacity){{

capacity *= 2;capacity *= 2;double[] newData = new double[] newData = new

double[capacity];double[capacity];for(int i = 0; i < data.length; i++)for(int i = 0; i < data.length; i++)

newData[i] = data[i];newData[i] = data[i];data = newData;data = newData;

}}data[dataSize] = x;data[dataSize] = x;dataSize++;dataSize++;

} } else else {{

stop = true;stop = true;}}

}}

Page 76: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

©2001 Deb Deppeler. All rights reserved.

Example: Candy in a Example: Candy in a MachineMachine

Create the 2D Create the 2D array with array with 3 rows and 3 rows and 5 columns.5 columns.

Assign prices Assign prices to each item.to each item.

machine[r][c] = ??machine[r][c] = ??

.50.50 .75.75 .45.45 .60.60 .85.85

.90.90 .80.80 .55.55 .70.70 .65.65

.40.40 .95.95 1.101.10 .30.30 .35.35

c=0 1 2 3 4

r=0

1

2

Page 77: Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all

©2001 Deb Deppeler. All rights reserved.

Example: Candy in a Example: Candy in a MachineMachine

Write a code fragment to increaseWrite a code fragment to increase the price of all items by 5 cents. the price of all items by 5 cents.

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

for ( int j=0; j < machine[i].length; j++ )for ( int j=0; j < machine[i].length; j++ )

machine[i][j] = machine[i][j] + 0.05;machine[i][j] = machine[i][j] + 0.05;