166
CHAPTER 7 Arrays and the ArrayList Class

Arrays and the ArrayList Class

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Arrays and the ArrayList Class

CHAPTER 7

Arrays and the

ArrayList Class

Page 2: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-2

Chapter Topics

Chapter 7 discusses the following main topics:

– Introduction to Arrays

– Processing Array Contents

– Passing Arrays as Arguments to Methods

– Some Useful Array Algorithms and Operations

– Returning Arrays from Methods

– String Arrays

– Arrays of Objects

Page 3: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-3

Chapter Topics

Chapter 7 discusses the following main topics:

– The Sequential Search Algorithm

– Parallel Arrays

– Two-Dimensional Arrays

– Arrays with Three or More Dimensions

– The Selection Sort and the Binary Search

– Command-Line Arguments

– The ArrayList Class

Page 4: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-4

Introduction to Arrays

• Primitive variables are designed to hold only one value at a

time. e.g., int number;

• Arrays allow us to create a collection of like values that are

indexed.

• An array can store any type of data but only one type of data

at a time.

• An array is a list of data elements.

e.g., int[ ] numbers;

707 727 737 … 787addr of …

numbers numbers[0] numbers[1] numbers[2] numbers[7]

Page 5: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-5

Introduction to Arrays

final int ARRAY_SIZE = 5;

int [] numbers = new int[ARRAY_SIZE];

numbers[0] = 25;

numbers[3] = 45;

25 0 0 45 0

numbers

variablenumbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

final int ARRAY_SIZE = 5;

int [] numbers = new int[ARRAY_SIZE];

numbers[0] = 25;

numbers[3] = 45;

Array element values are initialized to 0.

double dNumbers[] = new double[ARRAY_SIZE];

Page 6: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-6

Creating Arrays

• An array is an object so it needs an object reference.

// Declare a reference to an array that will

// hold integers.

int[] numbers;

• The next step creates the array and assigns its address to the

numbers variable.

// Create a new array that will hold 6 integers.

numbers = new int[6];

Array element values are initialized to 0.

Array indexes always start at 0.

0

index 0

0

index 1

0

index 2

0

index 3

0

index 4

0

index 5

numbers[0]

numbers[5]

Page 7: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-7

Creating Arrays

• It is possible to declare an array reference and create it

in the same statement.int[] numbers = new int[6]; numbers variable

numbers references an array

with memory for 6 int values

• Arrays may be of any type. Elem 0 Elem 1 ….. Elem 5

float[] temperatures = new float[100];

char[] letters = new char[41];

long[] units = new long[50];

double[] sizes = new double[1200];

Page 8: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-8

Creating Arrays

• The array size must be a non-negative number.

• It may be a literal value, a constant, or variable.

• Use a final variable as a size declarator.

final int ARRAY_SIZE = 6;

int[] numbers = new int[ARRAY_SIZE];

• Once created, an array size is fixed and cannot be changed.

Page 9: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_arrayDemos;import java.util.Random;

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

final int ARRAY_SIZE = 10;int numbers[] = new int[ARRAY_SIZE];for (int index = 0; index < ARRAY_SIZE; index++){

Random rand = new Random();numbers[index] = rand.nextInt(3)-1; //[-1, 2)

System.out.println(index + " " + numbers[index]);

}//end of for index...

System.out.println("\nThe numbers array has:");for (int i = 0; i < ARRAY_SIZE; i++){

System.out.printf("numbers [ %d ] is %d.\n", i, numbers[i]);

}//end of for i ...}//end of main

}

0 1

1 0

2 -1

3 0

4 1

5 1

6 0

7 -1

8 -1

9 0

Page 10: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

0 1

1 0

2 -1

3 0

4 1

5 1

6 0

7 -1

8 -1

9 0

The numbers array has:numbers [ 0 ] is 1.numbers [ 1 ] is 0.numbers [ 2 ] is -1.numbers [ 3 ] is 0.numbers [ 4 ] is 1.numbers [ 5 ] is 1.numbers [ 6 ] is 0.numbers [ 7 ] is -1.numbers [ 8 ] is -1.numbers [ 9 ] is 0.

Page 11: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_arrayDemos;import java.util.Random;

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

final int ARRAY_SIZE = 10;int [] numbers = new int[ARRAY_SIZE];for (int index = 0; index < ARRAY_SIZE; index++){

Random rand = new Random();numbers[index] = rand.nextInt(100)-50;//[-50, 50)System.out.println(index + " " +

numbers[index]);}//end of for index...

System.out.println("\nThe numbers array has:");for (int i = 0; i < ARRAY_SIZE; i++){

System.out.printf("numbers [ %d ] is %d.\n", i, numbers[i]);

}//end of for i ...}//end of main

}

0 -491 -252 93 -144 285 266 217 -258 119 -18

Page 12: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

0 -491 -252 93 -144 285 266 217 -258 119 -18

The numbers array has:numbers [ 0 ] is -49.numbers [ 1 ] is -25.numbers [ 2 ] is 9.numbers [ 3 ] is -14.numbers [ 4 ] is 28.numbers [ 5 ] is 26.numbers [ 6 ] is 21.numbers [ 7 ] is -25.numbers [ 8 ] is 11.numbers [ 9 ] is -18.

Page 13: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

//insert the following program segment at the end of the //previous program before “}//the end of main”

double dNumbers [] = new double[ARRAY_SIZE];Scanner kb = new Scanner(System.in);for (int index = 0; index < ARRAY_SIZE-5; index++) {

System.out.println("Enter a floating point number: ");dNumbers[index] = kb.nextDouble();

}System.out.println("\nThe numbers array has:");for (int i = 0; i < ARRAY_SIZE; i++){System.out.printf("the floating point numbers [ %d ] is

%.4f.\n", i, dNumbers[i]);\}//end of for i ...System.out.println("\nThe size of the array dNumber[] is

" + dNumbers.length);

Page 14: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Enter a floating point number: 20.4Enter a floating point number: 21.5Enter a floating point number: 22.6Enter a floating point number: 23.666666Enter a floating point number: 24.7777777

The numbers array has:the floating point numbers [ 0 ] is 20.4000.the floating point numbers [ 1 ] is 21.5000.the floating point numbers [ 2 ] is 22.6000.the floating point numbers [ 3 ] is 23.6667.the floating point numbers [ 4 ] is 24.7778.the floating point numbers [ 5 ] is 0.0000.the floating point numbers [ 6 ] is 0.0000.the floating point numbers [ 7 ] is 0.0000.the floating point numbers [ 8 ] is 0.0000.the floating point numbers [ 9 ] is 0.0000.

The size of the array dNumber[] is 10

Defined by default

Round off

Page 15: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-15

Accessing the Elements of an Array

• An array is accessed by:

– the reference name

– a subscript that identifies which element in the array to

access.

numbers[0] = 20; //pronounced "numbers sub zero"

numbers[0]

0

numbers[1]

0

numbers[2]

0

numbers[3]

0

numbers[4]

70

numbers[5]

20

numbers

numbers[5] = 70; //pronounced "numbers sub five"

Page 16: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-16

Inputting and Outputting Array Elements

• Array elements can be treated as any other variable.

• They are simply accessed by the same name and a

subscript.

• See example: ArrayDemo1.java

• Array subscripts can be accessed using variables (such

as for loop counters).

for (int index = 0; numbers[index] > 0 && index < 6; index++) {

System.out.printf(“numbers [ %d ] is %d.\n”, index, numbers[index]) };

• See example: ArrayDemo2.java

Page 17: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-17

Bounds Checking

• Array indexes always start at zero and continue to (array length - 1).

int [] values = new int[12];

size = values.length;//assign 12 to the size.

• This array would have indexes 0 through 11.

• See example: InvalidSubscript.java

• In for loops, it is typical to use i, j, and k as counting variables.

– It might help to think of i as representing the word index.

Page 18: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_arrayDemos;import java.util.Random;

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

final int ARRAY_SIZE = 10;int numbers[] = new int[ARRAY_SIZE];for (int index = 0; index < ARRAY_SIZE-2; index++){

Random rand = new Random();numbers[index] = rand.nextInt(100)-50;System.out.println(index + " " + numbers[index]);

}//end of for index...

System.out.println("The size of array numbers is " + numbers.length + "\n\nThe numbers array has:");for (int i = 0; i < ARRAY_SIZE; i++){

System.out.printf("numbers [ %d ] is %d.\n", i, numbers[i]);}//end of for i ...

}//end of main}

Page 19: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

0 -121 492 -223 -314 -15 426 -267 -5The size of array numbers is 10

The numbers array has:numbers [ 0 ] is -12.numbers [ 1 ] is 49.numbers [ 2 ] is -22.numbers [ 3 ] is -31.numbers [ 4 ] is -1.numbers [ 5 ] is 42.numbers [ 6 ] is -26.numbers [ 7 ] is -5.numbers [ 8 ] is 0.numbers [ 9 ] is 0.

Page 20: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

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

System.out.printf("numbers [ %d ] is %d.\n", i, numbers[i]);

}//end of for i ...

The numbers array has:numbers [ 0 ] is -14.numbers [ 1 ] is -1.numbers [ 2 ] is -42.numbers [ 3 ] is -6.numbers [ 4 ] is -19.numbers [ 5 ] is -46.numbers [ 6 ] is 45.numbers [ 7 ] is 20.numbers [ 8 ] is 0.numbers [ 9 ] is 0.

Page 21: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-21

Off-by-One Errors

• It is very easy to be off-by-one when accessing arrays.

// This code has an off-by-one error.

int[] numbers = new int[100];

int[] numbers_i = new int[100];

for (int i = 1; i <= 100; i++){

numbers[i] = 99;

numbers_i[i] = i;}

• Here, the equal sign allows the loop to continue on to index 100, where 99 is the last index in the array.

• This code would throw an ArrayIndexOutOfBoundsException.

Page 22: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

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

System.out.printf("numbers [ %d ] is %d.\n", i, numbers[i]);

}//end of for i ...

The numbers array has:numbers [ 0 ] is 18.numbers [ 1 ] is -15.numbers [ 2 ] is -19.numbers [ 3 ] is -37.numbers [ 4 ] is 27.numbers [ 5 ] is -16.numbers [ 6 ] is 23.numbers [ 7 ] is 44.numbers [ 8 ] is 0.numbers [ 9 ] is 0.Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10at ch07_arrayDemos.Chap07_ArrayDemos.main(Chap07_ArrayDemos.java:21)

Page 23: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-23

Array Initialization

//use new keyword to create an array object

int[ ] days = new int[12];

// or

int [ ] days;

days = new int[12];

// or

final int DAYS_SIZE = 12;

int [ ] days = new int[DAYS_SIZE];

•See example: ArrayInitialization.java

0 0 0 0 0 0 0 0 0 0 0 0

days

Page 24: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-24

Array Initialization

//use new keyword to create an array object

int[ ] days = new int[12];

//Or

int [ ] days;

days = new int[12];

• Once an array is created, its size cannot be changed.

• By default, Java initializes array elements with 0.

• Java performs array bounds checking, which means that it does not

allow a statement to use a subscript that is outside the range of valid

subscripts for an array. The valid subscripts for the array days are 0

through 11.

•See example: ArrayInitialization.java

0 0 0 0 0 0 0 0 0 0 0 0

days

Page 25: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-25

Array Initialization

• When relatively few items need to be initialized, an

initialization list can be used to initialize the array.

int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

• The numbers in the list are stored in the array in order:

– days[0] is assigned 31,

– days[1] is assigned 28,

– days[2] is assigned 31,

– days[3] is assigned 30,

– etc.

– days[11] is assigned 31.

• See example: ArrayInitialization.java

Page 26: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_01ArrayDemos;

public class Chap07_01ArrayDemos {

public static void main(String[] args) {

int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

String str = "\nDays[%d] = %d.";

for (int index = 0; index < 12; index++)

{

System.out.printf(str, index, days[index]);

}//end for

}//end main

}

Days[0] = 31.

Days[1] = 28.

Days[2] = 31.

Days[3] = 30.

Days[4] = 31.

Days[5] = 30.

Days[6] = 31.

Days[7] = 31.

Days[8] = 30.

Days[9] = 31.

Days[10] = 30.

Days[11] = 31

Page 27: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int [] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};for (int i = 0; i < days.length; i++){

System.out.printf("Month[ %d ] has %d days\n", i, days[i]);

}System.out.println("\nThe end.\n"); Month[ 0 ] has 31 days

Month[ 1 ] has 28 daysMonth[ 2 ] has 31 daysMonth[ 3 ] has 30 daysMonth[ 4 ] has 31 daysMonth[ 5 ] has 30 daysMonth[ 6 ] has 31 daysMonth[ 7 ] has 31 daysMonth[ 8 ] has 30 daysMonth[ 9 ] has 31 daysMonth[ 10 ] has 30 daysMonth[ 11 ] has 31 days

The end.

Page 28: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-28

Alternate Array Declaration

• Previously we showed arrays being declared:

declare an array variable numbers which does not create an array.

int[] numbers;

However, the brackets can also go here:

int numbers[];

These are equivalent but the first style is typical.

Then use the new key word to create an array and assigned it address to the numbers variable.

numbers = new int[6];

Or we simply write

int [ ] numbers = {101, 102, 103, 104, 105};

Page 29: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int numbers[];

numbers = new int[6];

String str1 = "\nnumbers[%d] has %d";

for (int index = 0; index < 6; index++)

{

System.out.printf(str1, index, numbers[index]);

}//end for

numbers[0] has 0

numbers[1] has 0

numbers[2] has 0

numbers[3] has 0

numbers[4] has 0

numbers[5] has 0

Page 30: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int numbers[];

numbers = new int[6];

numbers = {101, 102, 103, 104, 105, 106};

String str1 = "\nnumbers[%d] has %d";

for (int index = 0; index < 6; index++)

{

System.out.printf(str1, index, numbers[index]);

}//end for

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Array constants can only be used in initializers

at

ch07_01ArrayDemos.Chap07_01ArrayDemos.main(Chap07_01ArrayD

emos.java:15)

Page 31: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

//int numbers[];

//numbers = new int[6];

int [] numbers = {101, 102, 103, 104, 105, 106};

String str1 = "\nnumbers[%d] has %d";

for (int index = 0; index < 6; index++)

{

System.out.printf(str1, index, numbers[index]);

}//end for

numbers[0] has 101

numbers[1] has 102

numbers[2] has 103

numbers[3] has 104

numbers[4] has 105

numbers[5] has 106

Page 32: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

numbers[0] has 101

numbers[1] has 102

numbers[2] has 103

numbers[3] has 104

numbers[4] has 105

numbers[5] has 106

int numbers[];

numbers = new int[6];

String str1 = "\nnumbers[%d] has %d";

int value = 100;

for (int index = 0; index < 6; index++)

{

numbers[index] = ++value;

}//end for

for (int index = 0; index < 6; index++)

{

System.out.printf(str1, index, numbers[index]);

}//end for

Page 33: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

double [] nos = {101.011, 102.016, 103.026, 104.037, 105.048};

for (int index = 0; index < 5; index++)

{

System.out.printf("\nnos[%d] has %.2f", index, nos[index]);

}//end for

nos[0] has 101.01

nos[1] has 102.02

nos[2] has 103.03

nos[3] has 104.04

nos[4] has 105.05

Round off

Page 34: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-34

Alternate Array Declaration

• Previously we showed arrays being declared:int[] numbers;

– However, the brackets can also go here:

int numbers[];

– These are equivalent but the first style is typical.

• Multiple arrays can be declared on the same line.int[] numbers, codes, scores;

• With the alternate notation each variable must have brackets.int numbers[], codes[], scores;

– The scores variable in this instance is simply an int variable.

Page 35: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-35

Processing Array Contents

• Array elements can be used in relational operations:

if(cost[20] < cost[0])

{

//statements

}

• They can be used as loop conditions:

while(value[count] != 0)

{

//statements

}

Page 36: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_02ArrayDemos;

public class Chap07_02ArrayDemos {

public static void main(String[] args) {

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};

int count = 0;

while (iD[count] != 0)

{

System.out.printf("\niD[ %d ] is %d.", count, iD[count]);

count ++;

}

System.out.println("\nTotal number of iD is " + count);

System.out.println("Total array size of iD is " + iD.length);

}//end of main

}

Page 37: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

iD[ 0 ] is 1011.

iD[ 1 ] is 1012.

iD[ 2 ] is 1013.

iD[ 3 ] is 1015.

Total number of iD is 4

Total array size of iD is 10

Output of the program is:

Page 38: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-38

Processing Array Contents

• Processing data in an array is the same as any other variable.

grossPay = hours[3] * payRate;

• Pre and post increment works the same for the content of array

score[i]:

int[] score = {7, 8, 3, 10, 11};

++score[2]; // Pre-increment operation

score[4]++; // Post-increment operation

• See example: PayArray.java

• System.out.println(++score[2] + “ ” + score[2]);

• System.out.println(score[4]++ + “ ” + score[4]);

Page 39: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int [] score = {7, 8, 9, 10, 11};System.out.printf("score[2] is %d, and then %d " +

"and then %d.\n" ,score[2], ++score[2], score[2]);

System.out.printf("score[4] is %d, and then %d, " + "and then %d." , score[4], score[4]++, score[4]);

score[2] is 9, and then 10 and then 10.score[4] is 11, and then 11, and then 12.

Page 40: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};

int count = -1;

while (iD[++count] != 0)

{

System.out.printf("\niD[ %d ] is %d.", count, iD[count]);

}

System.out.println("\nTotal number of iD is " + count);

System.out.println("Total array size of iD is " + iD.length);

Can it be used for indexing an array? Yes, but be careful!

iD[ 0 ] is 1011.

iD[ 1 ] is 1012.

iD[ 2 ] is 1013.

iD[ 3 ] is 1015.

Total number of iD is 4

Total array size of iD is 10

Page 41: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};

int count = 0;

while (iD[count++] != 0)

{

System.out.printf("\niD[ %d ] is %d.", count, iD[count]);

}

System.out.println("\nTotal number of iD is " + (count));

System.out.println("Total array size of iD is " + iD.length);

iD[ 1 ] is 1012.

iD[ 2 ] is 1013.

iD[ 3 ] is 1015.

iD[ 4 ] is 0.

Total number of iD is 5

Total array size of iD is 10

Can it be used for indexing an array? Yes, but be careful!

Here is a problem!!!!

Page 42: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int count = 0;while (iD[count] != 0){ System.out.printf("\niD[ %d ] is %d.", count, iD[count++]);

}//end of whileSystem.out.println("\nTotal number of iD is " + count);System.out.println("Total array size of iD is " + iD.length);

iD[ 0 ] is 1011.iD[ 1 ] is 1012.iD[ 2 ] is 1013.iD[ 3 ] is 1015.Total number of iD is 4Total array size of iD is 10

Page 43: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};int count = 0;while (iD[count] != 0){ System.out.printf("\niD[ %d ] is %d.", count, ++iD[count++]);

}//end of whileSystem.out.println("\nTotal number of iD is " + count);System.out.println("Total array size of iD is " + iD.length);

iD[ 0 ] is 1012.iD[ 1 ] is 1013.iD[ 2 ] is 1014.iD[ 3 ] is 1016.Total number of iD is 4Total array size of iD is 10

Page 44: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

I an’t do it!

Page 45: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};

int count = 0;

while (iD[count++] != 0)

{

System.out.printf("\niD[ %d ] is %d.", count-1, iD[count-1]);

}

System.out.println("\nTotal number of iD is " + (count-1));

System.out.println("Total array size of iD is " + iD.length);

Can it be used for indexing an array? Yes, but be careful!

A correction

iD[ 0 ] is 1011.

iD[ 1 ] is 1012.

iD[ 2 ] is 1013.

iD[ 3 ] is 1015.

Total number of iD is 4

Total array size of iD is 10

Page 46: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-46

The Enhanced for Loop

• Simplified array processing (read only)

• Always goes through all elements

• General format:

for(datatype elementVariable : array)

statement;

Page 47: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-47

The Enhanced for Loop

Example:

//create an object array with the variable numbers as

// reference to

int[] numbers = {3, 6, 9};

for(int val : numbers)

{

System.out.println("The next value is " +

val);

} for (int i = 0; i < 3; i++)

{

System.out.println("The next value is "

+ numbers[i]);

}

Page 48: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-48

The Enhanced for Loop

Example:

int[] numbers = {3, 6, 9};

for(int numbersContents : numbers)

{

System.out.println("The next value is " +

numbersContents);

}

Output;

The next value is 3

The next value is 6

The next value is 9

Page 49: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-49

Array Length

• Arrays are objects and provide a public field named length

that is a constant that can be tested.

double[] temperatures = new double[25];

The length of this array is 25.

• The length of an array can be obtained via its length constant.

int size = temperatures.length;

The variable size will contain 25.

• Cannot change the value of an array’s length field.

Page 50: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-50

Array Size

• The length constant can be used in a loop

to provide automatic bounding.

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

{

System.out.println("Temperature " + i ": "

+ temperatures[i]);

}

Index subscripts start at 0 and end at one less than the

array length.

Page 51: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-51

Array Size

• You can let the user specify the size of an array:

int numTests;

int[] tests;

Scanner keyboard = new Scanner(System.in);

System.out.print("How many tests do you have?");

numTests = keyboard.nextInt();

tests = new int[numTests];

• See example: DisplayTestScores.java

Page 52: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

import java.util.Scanner;

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

int numTests;int[] tests;Scanner keyboard = new Scanner(System.in);System.out.print("How many tests do you have?");numTests = keyboard.nextInt();tests = new int[numTests];

System.out.print("tests array's length is " + tests.length + "\n");

for (int index=0; index < tests.length; index++) {System.out.print(tests[index] + " "); }

}} How many tests do you have?8

tests array's length is 80 0 0 0 0 0 0 0

Page 53: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-53

Reassigning Array References

• An array reference can be assigned to another array of

the same type.

// Create an array referenced by the numbers

// variable.

int[] numbers = new int[10];

// Reassign numbers to a new array.

numbers = new int[5];

• If the first (10 element) array no longer has a reference

to it, it will be garbage collected.

numbers

Page 54: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-54

Reassigning Array References

• An array reference can be assigned to another array of

the same type.

// Create an array referenced by the numbers

// variable.

int[] numbers = new int[10];

int []numbersc = numbers; //a reference copy

// Reassign numbers to a new array.

numbers = new int[5];

• If the first (10 element) array no longer has a reference

to it, it will be garbage collected.

numbers

numbersc

Page 55: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

import java.util.Scanner;

public class arrayLecture07 {

public static void main(String[] args) {

int numTests;

double [] tests;

Scanner keyboard = new Scanner(System.in);

System.out.print("How many tests do you have?");

numTests = keyboard.nextInt();

tests = new double[numTests];

System.out.print("tests array's length is " + tests.length + "\n");

for (int index=0; index < tests.length; index++) {

System.out.print("Enter the " + index + " score:");

tests[index] = keyboard.nextDouble(); }

for (int index=0; index < tests.length; index++) {

System.out.print(tests[index] + " "); }

//continue to the next slide

Page 56: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

tests = new double[5];

System.out.print("\ntests array's length is " + tests.length + "\n");

for (int index=0; index < tests.length; index++) {

System.out.print("Enter the " + index + " score:");

tests[index] = keyboard.nextDouble(); }

for (int index=0; index < tests.length; index++) {

System.out.print(tests[index] + " "); }

} //end of main

} How many tests do you have?3

tests array's length is 3

Enter the 0 score:100

Enter the 1 score:101

Enter the 2 score:99

100.0 101.0 99.0

tests array's length is 5

Enter the 0 score:95.01

Enter the 1 score:95.02

Enter the 2 score:95.03

Enter the 3 score:95.04

Enter the 4 score:95.05

95.01 95.02 95.03 95.04 95.05

100.0 101.0 99.0

95.01 95.02 95.03 95.04 99.05

test

Before the end of execution of the

second for loop.

Page 57: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-57

Reassigning Array References

Address

The numbers variable

holds the address of an

int array.

int[] numbers = new int[10];

numbers

numbers[1]numbers[9]numbers[0]

Page 58: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-58

Reassigning Array References

AddressThe numbers variable

holds the address of anint array.

numbers = new int[5];

This array gets marked for

garbage collection

int[] numbers = new int[10];

Page 59: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-59

Copying Arrays

• This is not the way to copy an array.int[] array1 = { 2, 4, 6, 8, 10 };

int[] array2 = array1; // This does not copy array1.

// a reference copy.

• 2

Addressarray1 holds an

address to the array

Addressarray2 holds an

address to the array

4 6 8 10

Example:

SameArray.java

Page 60: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-60

Copying Arrays

• This is not the way to copy an array.int[] array1 = { 2, 4, 6, 8, 10 };

int[] array2 = array1; // This does not copy array1.

2

Addressarray1 holds an

address to the array

Addressarray2 holds an

address to the array

4 6 8 10

Example: SameArray.java

array1

array2

// This statement is to set array2 to reference the same array.

int [ ] array1 = new int[5];

Or

int [ ] array1;

array1 = new int[5];

This type of assignment operation

is called a reference copy.

Namely, only the address of the

array object is copied, not the

contents of the array object.

Page 61: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_ArrayDemos01;

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

int[] array1 = { 2, 4, 6, 8, 10 };int[] array2 = array1; //reference copySystem.out.print("The array1 has ");for (int ix = 0; ix < 5; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );

}//end of forSystem.out.print("The array2 has ");for (int ix = 0; ix < 5; ix++) {

array2[ix] = array2[ix] + ix;if (ix < 4)System.out.print(array2[ix] + ", " );elseSystem.out.println(array2[ix] + ". " );

}//end of for//Prove "int[] array2 = array1;" is reference copy! System.out.print("The array1 has ");for (int ix = 0; ix < 5; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );elseSystem.out.println(array1[ix] + ". " );

}//end of for}//end of main

}

Page 62: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The array1 has 2, 4, 6, 8, 10. The array2 has 2, 5, 8, 11, 14. The array1 has 2, 5, 8, 11, 14.

The output of the program:

These output data shows that int[] array2 = array1; is a reference copy, but not copy an array1 to another array2.

Page 63: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_ArrayDemos01;

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

int[] array1 = { 2, 4, 6, 8, 10 };int[] array2 = new int[5]; //create an array object referenced by array2.System.out.print("The array1 has ");for (int ix = 0; ix < 5; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );

}//end of forSystem.out.print("The array2 has ");for (int ix = 0; ix < 5; ix++) {

if (ix < 4)System.out.print(array2[ix] + ", " );

elseSystem.out.println(array2[ix] + ". " );

}//end of for//Prove "int[] array2 and int array1;" are two different arrays.System.out.print("The array1 has ");for (int ix = 0; ix < 5; ix++){

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );

}//end of for}//end of main

}

Page 64: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The array1 has 2, 4, 6, 8, 10.

The array2 has 0, 0, 0, 0, 0.

The array1 has 2, 4, 6, 8, 10.

The output of the program:

Page 65: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-65

Copying Arrays• You cannot copy an array by merely assigning one

reference variable to another.

• You need to copy the individual elements of one array to another.

int[] firstArray = {5, 10, 15, 20, 25 };

int[] secondArray = new int[5];

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

secondArray[i] = firstArray[i];

• This code copies each element of firstArray to the corresponding element of secondArray.

Page 66: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-66

Copying Arrays

• You cannot copy an array by merely assigning one reference variable to another. (secondArray = firstArray; Wrong!)

• You need to copy the individual elements of one array to another.

int[] firstArray = {5, 10, 15, 20, 25 };

int[] secondArray = new int[5];

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

{secondArray[i] = firstArray[i];}

• This code copies each element of firstArray to the corresponding element of secondArray.

5 10 15 20 25

5 10 15 20 25

address

secondArray

firstArray

address

Page 67: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_ArrayDemos01;

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

int[] array1 = { 2, 4, 6, 8, 10 };int[] array2 = new int[5]; //an object referenced by array2.System.out.print("The array1 has ");//reverse copy the contents of array1 to array2.int array2SIZE = array2.length;for (int ix = 0; ix < array1.length; ix++){ //reverse-copy the array1 into array2

array2[array2SIZE-1 - ix] = array1[ix];}for (int ix = 0; ix < array1.length; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );}//end of for

Page 68: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

System.out.print("The array2 has ");for (int ix = 0; ix < array2.length; ix++) {

if (ix < 4)System.out.print(array2[ix] + ", " );

elseSystem.out.println(array2[ix] + ". " );

}//end of for//Prove that int[] array1 remains as it is. System.out.print("The array1 has ");for (int ix = 0; ix < array1.length; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );

}//end of for}//end of main

}

Page 69: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The array1 has 2, 4, 6, 8, 10. The array2 has 10, 8, 6, 4, 2. The array1 has 2, 4, 6, 8, 10.

The output of the program:

Page 70: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-70

Passing Array Elements to a Method

• When a single element of an array is passed to a

method it is handled like any other variable.

• See example: PassElements.java

• More often you will want to write methods to process

array data by passing the entire array, not just one

element at a time.

Page 71: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-71

Passing Arrays as Arguments

• Arrays are objects.

• Their references can be passed to methods like any

other object reference variable.

5 10 15 20 25

Address

showArray(numbers);30 35 40

public static void showArray(int[] array){

for (int i = 0; i < array.length; i++)System.out.print(array[i] + " ");

}

Example: PassArray.java

int [] numbers = {5, 10, 15, 20, 25, 30, 35, 40};

Page 72: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_ArrayDemos01;

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

int[] array1 = { 2, 4, 6, 8, 10 };int[] array2 = new int[10]; //an object referenced by array2.System.out.print("The array1 has ");//copy the contents of array1 to larger array2.int array2Size = array2.length;int array1Size = array1.length;for (int ix = 0; ix < array1Size; ix++){ //reverse-copy the array1 into larger array2

int ir = array1Size-1 - ix;array2[ix] = array1[ir];

}//end of forfor (int ix = 0; ix < array1Size; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );

}//end of for

Page 73: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

System.out.print("The array2 has ");for (int ix = 0; ix < array2Size; ix++) {

if (ix < array2Size-1)System.out.print(array2[ix] + ", " );

elseSystem.out.println(array2[ix] + ". " );

}//end of for//Prove that int[] array1 remains as it is. System.out.print("The array1 has ");for (int ix = 0; ix < array1Size; ix++) {

if (ix < 4)System.out.print(array1[ix] + ", " );

elseSystem.out.println(array1[ix] + ". " );

}//end of for

String str1 = "The array1 has ";String str2 = "\nThe array2 has ";showArray(str1, array1);showArray(str2, array2);

}//end of main

Page 74: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

//}end of mainpublic static void showArray(String str, int[] array){

System.out.println("\n" + str);for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + " ");}//end of for

}//end of showArray

}//end of class

Page 75: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The array1 has 2, 4, 6, 8, 10.

The array2 has 10, 8, 6, 4, 2, 0, 0, 0, 0, 0.

The array1 has 2, 4, 6, 8, 10.

The array1 has

2 4 6 8 10

The array2 has

10 8 6 4 2 0 0 0 0 0

The output of the program:

Page 76: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-76

Passing Array Elements to a Method

• When a single element of an array is passed to a method it is

handled like any other variable.

public class PassElements{

public static void main(String[ ] args){

int [] nos = {5, 10, 15, 20, 25};

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

displayElement(nos[i]); } //end for

} //end main

public static void displayElement(int content){

System.out.print(content + “, ”);}//end displayElement

} content

The program output is 5, 10, 15, 20, 25,

5 10 15 20 25

25

nos

nos[4]

address

Page 77: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-77

Passing Array Elements to a Method

• When a single element of an array is passed to a method it is

handled like any other variable.

int [] nos = {5, 10, 15, 20, 25};

int i = 0;

displayElement(nos[i], nos[i+1], nos[i+2], nos[i+3], nos[i+4]);

// displayElement(nos[0], nos[1], nos[2], nos[3], nos[4]);

public static void displayElement(int c0, int c1, int c2, intc3, int c4){

System.out.print(c0 + “, ” + c1 + “, ” + c2 + “, ” + c3 + “, ” + c4 +

“, ” );}//end displayElement. An awkward way!

The program output is 5, 10, 15, 20, 25,

5 10 15 20 25

5

c0

10c1

address

nos

nos[0] nos[1]

Page 78: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public class PassElements{

public static void main(String[ ] args){

int [] nos = {5, 10, 15, 20, 25};

int i = 0;

displayElement(nos[i], nos[i+1], nos[i+2], nos[i+3], nos[i+4]);

// displayElement(nos[0], nos[1], nos[2], nos[3], nos[4]);

} //end main

public static void displayElement(int c0, int c1, int c2, intc3, int c4){

System.out.print(c0 + “, ” + c1 + “, ” + c2 + “, ” + c3 + “, ” +

c4 + “, ” );

}//end displayElement. An awkward way!

}

The output is: 5, 10, 15, 20, 25

Page 79: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-79

Passing Array as Arguments to a Method

• More often you will want to write methods to process array data

by passing the entire array, not just one element at a time.

• When pass an array as an argument, it simply pass the value in

the variable that reference the array, as shown below

public static void main(String[ ] args){

int [] numbers = {5, 10, 15, 20, 25, 30, 35, 40};

showArray(numbers);

}

public static void showArray(int[] array) {

… }

• ..

5 10 15 20 25 30 35 40

address

array

number

address A reference copy!

Page 80: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-80

Passing Arrays as Arguments

• Arrays are objects.

• Their references can be passed to methods like any

other object reference variable.

5 10 15 20 25

Address

showArray(numbers); 30 35 40

public static void showArray(int[] array)

{

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

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

} Example: PassArray.java

Page 81: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public class PassArrayReferenceVariable{

public static void main(String[ ] args){

int [] numbers = {5, 10, 15, 20, 25, 30, 35, 40};

showArray(numbers);

} //end main

public static void showArray(int [] arrayContents) {

System.out.print(arrayContents);

System.out.print("\n");

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

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

} //end of showArray}}

The output is:

[I@15db9742

5 10 15 20 25 30 35 40

Page 82: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_02ArrayDemos;

public class Chap07_02ArrayDemos {

public static void main(String[] args) {

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};

displayArray(iD);

}//end of main

public static void displayArray(int [] queue) {

int count = 0;

while (queue[count] != 0)

{

System.out.printf("\niD[ %d ] is %d.", count, queue[count]);

count ++;

}

System.out.println("\nTotal number of iD is " + (count));

System.out.println("Total array size of iD is " + queue.length);

System.out.println("iD has the address of the array" + queue);

}//end of displayArray

}

Page 83: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The output is:

iD[ 0 ] is 1011.

iD[ 1 ] is 1012.

iD[ 2 ] is 1013.

iD[ 3 ] is 1015.

Total number of iD is 4

Total array size of iD is 10

iD has the address of the array[I@15db9742

Page 84: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The following main method:

displayArray(iD, striD, striD1);

copyArray(iD, iDCopied);

public static void displayArray(int [] queue, String str, String str0) {

}

public static void copyArray(int[] queue, int[] queue2) {

displayArray(queue2, str2, str3);

}

Page 85: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_02ArrayDemos;

public class Chap07_02ArrayDemos {

public static void main(String[] args) {

int [] iD = {1011, 1012, 1013, 1015, 0, 0, 0, 0, 0, 0};

int [] iDCopied = new int [15];

String striD = "\niD[ %d ] is %d.";

String striD1 = "iD";

displayArray(iD, striD, striD1);

copyArray(iD, iDCopied);

}//end of main

public static void displayArray(int [] queue, String str, String str0) {

int count = 0;

for(; count < queue.length; count++)

{

System.out.printf(str, count, queue[count]);

}

System.out.println("\nTotal number of " + str0 + " is " + (count));

System.out.println("Total array size of " + str0 + " is " + queue.length);

System.out.println(str0 + " has the address of the array" + queue);

}//end of displayArray

Page 86: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public static void copyArray(int[] queue, int[] queue2) {

int count = 0;

while (queue[count] != 0)

{

queue2[count] = queue[count];

count ++;

}

String str2 = "\niDCopied[ %d ] is %d.";

String str3 = "iDCopied";

displayArray(queue2, str2, str3);

}//end of copyArray

}

Page 87: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The output is:

iD[ 0 ] is 1011.

iD[ 1 ] is 1012.

iD[ 2 ] is 1013.

iD[ 3 ] is 1015.

iD[ 4 ] is 0.

iD[ 5 ] is 0.

iD[ 6 ] is 0.

iD[ 7 ] is 0.

iD[ 8 ] is 0.

iD[ 9 ] is 0.

Total number of iD is 10

Total array size of iD is 10

iD has the address of the array[I@15db9742

iDCopied[ 0 ] is 1011.

iDCopied[ 1 ] is 1012.

iDCopied[ 2 ] is 1013.

iDCopied[ 3 ] is 1015.

iDCopied[ 4 ] is 0.

iDCopied[ 5 ] is 0.

iDCopied[ 6 ] is 0.

iDCopied[ 7 ] is 0.

iDCopied[ 8 ] is 0.

iDCopied[ 9 ] is 0.

iDCopied[ 10 ] is 0.

iDCopied[ 11 ] is 0.

iDCopied[ 12 ] is 0.

iDCopied[ 13 ] is 0.

iDCopied[ 14 ] is 0.

Total number of iDCopied is 15

Total array size of iDCopied is 15

iDCopied has the address of the

array[I@6d06d69c

Page 88: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

iDCopied[ 0 ] is 1011.

iDCopied[ 1 ] is 1012.

iDCopied[ 2 ] is 1013.

iDCopied[ 3 ] is 1015.

iDCopied[ 4 ] is 0.

iDCopied[ 5 ] is 0.

iDCopied[ 6 ] is 0.

iDCopied[ 7 ] is 0.

iDCopied[ 8 ] is 0.

iDCopied[ 9 ] is 0.

iDCopied[ 10 ] is 0.

iDCopied[ 11 ] is 0.

iDCopied[ 12 ] is 0.

iDCopied[ 13 ] is 0.

iDCopied[ 14 ] is 0.

Total number of iDCopied is 15

Total array size of iDCopied is 15

iDCopied has the address of the array[I@6d06d69c

Page 89: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-89

Comparing Arrays

• The == operator determines only whether array references point to the same array object.

int[] firstArray = { 5, 10, 15, 20, 25 };

int[] secondArray = { 5, 10, 15, 20, 25 };

if (firstArray == secondArray) //This is a mistake.

System.out.println("The arrays are the same.");

else

System.out.println("The arrays are not the same.");

The program output is

The arrays are not the same. ……………. Why?

5 10 15 20 25

5 10 15 20 25

firstArray

secondArray

Page 90: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Comparing Arrays: Example

7-90

int[] firstArray = { 2, 4, 6, 8, 10 };

int[] secondArray = { 2, 4, 6, 8, 10 };

boolean arraysEqual = true;int i = 0;

// First determine whether the arrays are the same size.if (firstArray.length != secondArray.length)

{ arraysEqual = false;}

// Next determine whether the elements contain the same data.while (arraysEqual && i < firstArray.length)

{

if (firstArray[i] != secondArray[i])

{ arraysEqual = false; }

i++;}

if (arraysEqual)

System.out.println("The arrays are equal.");

else

System.out.println("The arrays are not equal.");

Page 91: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-91

Useful Array Operations

• Finding the Highest Valueint [] numbers = new int[50];

int highest = numbers[0];

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

{

if (numbers[i] > highest)

highest = numbers[i];

}

• Finding the Lowest Valueint lowest = numbers[0];

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

{

if (numbers[i] < lowest)

lowest = numbers[i];

}

By default

numbers[0] = 0

numbers[1] = 0

numbers[49] = 0

highest and

lowest have

values which are

0.

Page 92: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public class HighestLowestValues{

public static void main(String[ ] args){

final int ARRAY_SIZE = 15;

int [] numbers01 = new int[ARRAY_SIZE ];

getValues(numbers01);

int highest = numbers01[0];

for (int index = 1; index < numbers01.length; index++)

{

if (numbers01[index] > highest)

highest = numbers01[index];

}

System.out.println("\nThe highest numbers is " + highest);

int lowest = numbers01[0];

for (int index = 1; index < numbers01.length; index++)

{

if (numbers01[index] < lowest)

lowest = numbers01[index];

}

System.out.println("The lowest numbers is " + lowest);

}//end of main

Page 93: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public static void getValues(int [] arrayNumbers){

Random randomNumbers = new Random();

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

arrayNumbers[i] = randomNumbers.nextInt(100)+1;

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

}

}

}//end of class HighestLowestValues

The output is:

79 77 56 3 3 96 18 18 25 98 63 93 69 30 36

The highest numbers is 98

The lowest numbers is 3

Page 94: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-94

Useful Array Operations

• Summing Array Elements:

int total = 0; // Initialize accumulator

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

total += units[i];

• Averaging Array Elements:

double total = 0; // Initialize accumulator

double average; // Will hold the average

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

{total += scores[i];}//end for_loop

average = total / scores.length;

• Example: SalesData.java, Sales.java

Page 95: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ArrayClass_7_HiLowPK;

import java.util.Random;

public class HighestLowestValues {

public static void main(String[] args) {final int ARRAY_SIZE = 15;int[] numbers01 = new int[ARRAY_SIZE];getValues(numbers01);int highest = numbers01[0];for (int index = 1; index < numbers01.length;

index++) {if (numbers01[index] > highest)

highest = numbers01[index];}System.out.println("\nThe highest numbers is "

+ highest);

Page 96: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

int lowest = numbers01[0];for (int index = 1; index < numbers01.length;

index++) {if (numbers01[index] < lowest)

lowest = numbers01[index];}System.out.println("The lowest numbers is "

+ lowest);

int total = findTotal(numbers01);System.out.printf("The total of the array" +

"numbers01 is %d" +"\nThe average is %.4f", total, (double)total/ARRAY_SIZE);

}// end of main

Page 97: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public static void getValues(int[] arrayNumbers) {Random randomNumbers = new Random();

for (int i = 0; i < arrayNumbers.length; i++) {arrayNumbers[i] = randomNumbers.nextInt(100)+1;System.out.print(arrayNumbers[i] + " ");

}}// end of getValues

public static int findTotal(int [] numbers) {int sum = 0;for (int i = 0; i < numbers.length; i++){

sum += numbers[i];}return sum;

} //end of findTotal}// end of class HighestLowestValues

Page 98: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-98

Partially Filled Arrays

• Typically, if the amount of data that an array must hold is unknown:

– size the array to the largest expected number of elements.

– use a counting variable to keep track of how much valid data is in the array.

int[] array = new int[100];

int count = 0;

int number;

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a number or -1 to quit: ");

number = keyboard.nextInt();

while (number != -1 && count <= 99)

{

array[count] = number;

count++;

System.out.print("Enter a number or -1 to quit: ");

number = keyboard.nextInt();

}

input, number and keyboard were

previously declared and keyboard

references a Scanner object

Page 99: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

System.out.println("\n");int[] array = new int[12];int count = 0;int number;Scanner keyboard = new Scanner(System.in);System.out.print("Enter a number or -1 to quit: ");number = keyboard.nextInt();while (number != -1 && count <= 11)

{array[count] = number;count++;System.out.print("Enter a number or -1 to quit: ");number = keyboard.nextInt();

}for (int i = 0; i < array.length; i++){System.out.print(array[i] + ", ");}System.out.println("End of array of size 12!");

Page 100: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Enter a number or -1 to quit: 6Enter a number or -1 to quit: 5Enter a number or -1 to quit: 4Enter a number or -1 to quit: 3Enter a number or -1 to quit: 2Enter a number or -1 to quit: 1Enter a number or -1 to quit: -16, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, End of array of size 12!

Page 101: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-101

Arrays and Files

• Saving the contents of an array to a file:

int[] numbers = {10, 20, 30, 40, 50};

FileWriter fwriter = new

FileWriter(“Values.txt”, true);//Apend data to the file

PrintWriter outputFile =

new PrintWriter(fwriter);

PrintWriter outputFile =

new PrintWriter ("Values.txt"); //open the file

//Write the array elements to the file

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

{outputFile.println(numbers[i]+ “\r”);}

outputFile.close();

10 20 30 40 50numbers

10

20

30

40

50

Values

Page 102: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-102

Arrays and Files

• Reading the contents of a file into an array:

final int SIZE = 5; // Assuming we know the size.

int[] numbers = new int[SIZE];

int i = 0;

File file = new File("Values.txt"); //open the file

Scanner inputFile = new Scanner(file);

while (inputFile.hasNext() && i < numbers.length)

{

numbers[i] = inputFile.nextInt();

i++;

}

inputFile.close();

Page 103: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_;import java.io.*;import java.util.Scanner;

public class chap07_ArrayOutputFile {

public static void main(String[] args) throws IOException {Int[] numbers = {10, 20, 30, 40, 50, 60};FileWriter fwriter =

new FileWriter("Numbers.txt", true);PrintWriter outputFile =

new PrintWriter(fwriter);for (int ix = 0; ix < numbers.length; ix++){

outputFile.println(numbers[ix] + "\r");System.out.println(numbers[ix]);

}outputFile.close();

//open the file File file = new File("Numbers.txt"); Scanner inputFile = new Scanner(file);while (inputFile.hasNext()){

int numbersi = inputFile.nextInt();System.out.println(numbersi);

Page 104: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_;import java.io.*;import java.util.Scanner;

public class chap07_ArrayOutputFile {public static void main(String[] args) throws

IOException {int[] numbers = {10, 20, 30, 40, 50, 60};FileWriter fwriter =

new FileWriter("Numbers.txt", true);PrintWriter outputFile =

new PrintWriter(fwriter);for (int ix = 0; ix < numbers.length; ix++){

outputFile.println(numbers[ix] + "\r");System.out.println(numbers[ix]);

}outputFile.close();

Page 105: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

//open the fileFile file = new File("Numbers.txt"); Scanner inputFile = new Scanner(file);while (inputFile.hasNext()){

int numbersi = inputFile.nextInt();System.out.println(numbersi);

}inputFile.close();

}//end of mail}

Page 106: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-106

Returning an Array Reference from Methods

• A method can return a reference to an array.

• The return type of the method must be declared as an array of

the right type.

public static double[] getArray()

{

double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 };

return array; //return a reference to the array

}

• The getArray method is a public static method that returns an

array of doubles.

• See example: ReturnArray.java

This method is returning a reference to the array of double type

1.2 2.3 4.5 6.7 8.9addressarray

Page 107: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-107

Returning an Array Reference from Methods

public class ReturnArray{

public static void main(String[] args){

double [] values;

values = getArray();

for(double num: values)

System.out.print(num + “ ”);

}//end main

public static double[] getArray()

{

double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 };

return array;

}//end of getArray

}

•See example: ReturnArray.java

1.2 2.3 4.5 6.7 8.9addressarray

address

values

Page 108: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ArrayClass_7_GReferencePK;

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

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

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

}// end of main

public static double[] getArray() {double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 };return array; // return a reference to the array

} // end of getArray;

} // end of class ReturnArrayReference

The output is: 1.2 2.3 4.5 6.7 8.9

Page 109: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Page 110: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-110

String Arrays

• Arrays are not limited to primitive data.

• An array of String objects can be created:

String[] names = { "Bill", "Susan", "Steven", "Jean" };

The names variable holds

the address to the array. A String array is an array

of references to String objects.Address

names[1]

names[0]

names[3]

names[2]

Example: MonthDays.java

“Bill”

“Susan”

“Steven”

“Jean”

address

address

address

address

Page 111: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-111

String Arrays

• If an initialization list is not provided, the new keyword must be

used to create the array:

final int SIZE = 4;

String[] names = new String[SIZE];

The names variable holds

the address to the array.

Address

names[1]

names[0]

names[3]

names[2]

A String array is an array

of references to String objects.

null

null

null

null

Page 112: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-112

String Arrays

• When an array is created in this manner, each element of the

array must be initialized.

The names variable holds

the address to the array.

Address

names[1]

names[0]

names[3]

names[2]

“Bill”

“Susan”

“Steven”

“Jean”

address

address

address

address

names[0] = "Bill";

names[1] = "Susan";

names[2] = "Steven";

names[3] = "Jean";

After these statements

execute, each elements

of the name array will

reference a String

object.

A String array is an array

of references to String objects.

Page 113: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package ch07_arrayDemos_06;

public class Ch07_ArrayDemos06 {

public static void main(String[] args) {String name = new String(“Tu Nguyen");System.out.printf("My name is %s\n", name);final int SIZE = 5;String [] names = new String[SIZE];names[0] = “Brianna";names[1] = "Eric Thompson";names[2] = null;names[3] = "Hanna E. Kennedy";

for (int i = 0; i < SIZE; i++) {System.out.printf("The names[ %d ] has %s\n", i, names[i]);

}

}//end of main}

Page 114: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The output is:

My name is Tu Nguyen.

The names[ 0 ] has Brianna.

The names[ 1 ] has Eric Thompson

The names[ 2 ] has null

The names[ 3 ] has Hanna E. Kennedy

The names[ 4 ] has null This null is defined by default

This null is given by the user.

Page 115: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-115

Calling String Methods On Array Elements

• String objects have several methods, including:– toUpperCase

– compareTo

– equals

– charAt

• Each element of a String array is a String object.

• Methods can be used by using the array name and index as before.

System.out.println(names[0].toUpperCase());

char letter = names[3].charAt(0);

if (names[1].compareTo(names[2]) == 0)… ;

//compareTo returns integer

if (names[i].equals(“John”))… ;//return Boolean value

Page 116: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

"Susanez".compareTo("SusanezabcBilla") has the integer value -8. //The 1st is 8 character shorter than 2nd string.

"SusanezabcBilla".compareTo("Susanez") has the integer value 8. //The 1st is 8 character longer than the 2nd string.

"SusanezabcBilla".compareTo("Susemen") has the integer value -4. //code(a) – code(e) = -4.

"Susemen".compareTo("SusanezabcBilla") has the integer value 4. //code(e) – code(a) = -4.

"Susemen".compareTo("Susemen") has the integer value 0. //The two strings are the same

if (names[1].compareTo(names[2]) == 0)… ;

//compareTo returns integer

Page 117: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

if (names[i].equals(“John”))… ;//return Boolean value

"Susanez".equals("SusanezabcBilla") has the boolean value false."SusanezabcBilla".equals("Susanez") has the bolean value false."SusanezabcBilla".equals("Susemen") has the boolean value false."Susemen".equals("SusanezabcBilla") has the bolean value false."Susemen".equals("Susemen") has the boolean value true.names[3].equals("Susemen") has the boolean value true.

Page 118: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-118

The length Field & The length Method

• Arrays have a final field named length.

• String objects have a method named length.

• To display the length of each string held in a String array:

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

System.out.println(names[i].length());

• An array’s length member is a field

– You do not write a set of parentheses after its name.

• A String’s length is a method

– You do write the parentheses after the name of the String class’s length method.

Page 119: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-119

The length Field & The length() Method

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

System.out.println(names[i].length());

names.length is 4. And the output names[i].length() are4

5

7

4

The names variable holds

the address to the array.

Address

names[1]

names[0]

names[3]

names[2]

“Bill”

“Susan”

“Steven”

“Jean”

address

address

address

address

names[0] = "Bill";

names[1] = "Susan";

names[2] = "Steven";

names[3] = "Jean";

After these statements

execute, each elements

of the name array will

reference a String

object.

A String array is an array

of references to String objects.

Page 120: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

final int SIZE = 10;String [] names = new String[SIZE];names[0] = "Peterj Ng, Sr.";names[1] = "Peteric Thompson";names[2] = "Hanna J. Kennore";names[3] = "Hanna E. Kennedy";names[4] = "Susanez";names[5] = null;

names[9] = "who are you?";for (int i = 0; i < SIZE; i++) {

System.out.printf("The names[ %d ] has %s\n", i, names[i]);}for (int i = 0; (i < names.length) && names[i]!= null; i++)

System.out.println(names[i].length());int i = 0;

while ((i < names.length))

{ while ( names[i] != null)

{System.out.println(names[i].length());

break;}

i++;

}

Page 121: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The names[ 1 ] has Peteric ThompsonThe names[ 2 ] has Hanna J. Kennore, Jr.The names[ 3 ] has Hanna E. KennedyThe names[ 4 ] has SusanezThe names[ 5 ] has nullThe names[ 6 ] has nullThe names[ 7 ] has nullThe names[ 8 ] has nullThe names[ 9 ] has who are you?14162116714162116712

Page 122: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-122

Arrays of Objects

• Because Strings are objects, we know that arrays can contain

objects.

• The following creates an array that can reference BankAccount

objects.

BankAccount[] accounts = new BankAccount[5];

The accounts variable holds the address

of an BankAccount array.

Address

null

null

null

null

accounts[1]

accounts[0]

accounts[3]

accounts[2]

nullaccounts[4]

The array is

an array of references to

BankAccount objects.

Page 123: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-123

Arrays of Objects

• Each element needs to be initialized.for (int i = 0; i < accounts.length; i++)

accounts[i] = new BankAccount();• //The BankAccount class has a no-arg constructor that assigns 0.0 to the balance field.

//After the loop executes, each element of the accounts array will reference a //BankAccount.

See example: ObjectArray.java

The accounts variable holds the address

of an BankAccount array.

Address

Address

Address

Address

Address

Address

balance: 0.0

balance:

balance:

balance:

balance:

0.0

0.0

0.0

0.0

accounts[1]

accounts[0]

accounts[3]

accounts[2]

accounts[4]BankAccount objects

Page 124: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-124

Arrays of Objects• Objects in an array are accessed with subscripts as if other data type in an array.

• The following code uses the accounts[2] element to call the setBalance and withdraw methods.:

accounts[2].setBalance(2500.00);

accounts[2].withdraw(500.00);

accounts[2].getBalance( );

The accounts variable holds the address

of an BankAccount array.

Address

Address

Address

Address

Address

Address

balance: 0.0

balance:

balance:

balance:

balance:

0.0

0.0

0.0

0.0

accounts[1]

accounts[0]

accounts[3]

accounts[2]

accounts[4]BankAccount objects

Page 125: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package BankingAccountPK;

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

//create an array that can reference BankAccount objectsBankAccount[] accounts = new BankAccount[5];for (int i = 0; i < accounts.length; i++) {

System.out.println("Content of accounts[" +i + "] is " + accounts[i]);

}

for (int i = 0; i < accounts.length; i++)accounts[i] = new BankAccount();

for (int i = 0; i < accounts.length; i++){System.out.println("accounts[" +

i + "] has balance of " + accounts[i].getBalance());

}//to be continued

Page 126: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

accounts[1].deposit(2500.00);accounts[4].deposit(7500.00);for (int i = 0; i < accounts.length; i++){

System.out.println("accounts[" +i + "] has balance of " + accounts[i].getBalance());

}

accounts[4].deposit(2500.00);double cashout = accounts[4].withdraw(3000.00);System.out.println("Cashout amount is " + cashout +

"\nYour account new balance is " +accounts[4].getBalance());

}//end of main}

Page 127: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package BankingAccountPK;

public class BankAccount {private double balance;

public BankAccount() {balance = 0.0;

}

public BankAccount(double initialAmt) {balance = initialAmt;

}

public double getBalance() {return balance;

}

//to be continued

Page 128: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

public double withdraw(double withdrawAmt) {if (balance < withdrawAmt){ double currentBalance = balance;

balance = balance - currentBalance;//return to client the withdrawAmtreturn currentBalance;

}else {

balance = balance - withdrawAmt;//return to client the withdrawAmtreturn withdrawAmt;

}}

public double deposit(double depositAmt) {balance = balance + depositAmt;return balance;

}}//end of class BankAccount

Page 129: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Content of accounts[0] is nullContent of accounts[1] is nullContent of accounts[2] is nullContent of accounts[3] is nullContent of accounts[4] is nullaccounts[0] has balance of 0.0accounts[1] has balance of 0.0accounts[2] has balance of 0.0accounts[3] has balance of 0.0accounts[4] has balance of 0.0accounts[0] has balance of 0.0accounts[1] has balance of 2500.0accounts[2] has balance of 0.0accounts[3] has balance of 0.0accounts[4] has balance of 7500.0Cashout amount is 3000.0Your account new balance is 7000.0

Page 130: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

BankingAccount

src

BankingAccountPK

AccountBanking.java

BankAccount.java

Page 131: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-131

The Sequential Search Algorithm

• A search algorithm is a method of locating a specific item in a larger collection of data.

• The sequential search algorithm uses a loop to:

– sequentially step through an array,

– compare each element with the search value, and

– stop when

• the value is found or

• the end of the array is encountered.

• See example: SearchArray.java

Page 132: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-132

The Sequential Search Algorithm

Algorithm SequentialSearch(A[0 .. n-1], K)

// Searches for a given value in a given array by sequential search

Input: An array A[0 .. n-1] and a search key K

Output: The index of the first element of A that matches K

or -1 if there are no matching elements

i := 0;

while (i < n and A[i] ≠ K) do {

i := i + 1;

}

if i < n return i

else return -1;

Page 133: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-133

The Binary Search Algorithm

Page 134: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-134

Two-Dimensional Arrays

• A two-dimensional array is an array of arrays.

• It can be thought of as having rows and columns.

row 0

column 1 column 2 column 3column 0

row 1

row 2

row 3

Begin

here

11/25

/2018

Page 135: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-135

• Declaring a two-dimensional array requires two sets of brackets and two size declarators

– The first one is for the number of rows

– The second one is for the number of columns.

double[][] scores = new double[3][4];

• The two sets of brackets in the data type indicate that the scores variable will reference a two-dimensional array.

• Notice that each size declarator is enclosed in its own set of brackets.

Two-Dimensional Arrays

two dimensional array rows columns

Page 136: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-136

Accessing Two-Dimensional Array Elements

• When processing the data in a two-dimensional array,

each element has two subscripts:

– one for its row and

– another for its column.

Page 137: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-137

Accessing Two-Dimensional Array

Elements

scores[0][3]scores[0][2]scores[0][1]scores[0][0]row 0

column 1 column 2 column 3column 0

row 1

row 2

The scores variable

holds the address of a2D array of doubles.

Address

scores[1][3]scores[1][2]scores[1][1]scores[1][0]

scores[2][3]scores[2][2]scores[2][1]scores[2][0]

double[][] scores = new double[3][4];

Page 138: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-138

Accessing Two-Dimensional Array

Elements

Accessing one of the elements in a two-

dimensional array requires the use of both

subscripts.

scores[2][1] = 95;

0000row 0

column 1 column 2 column 3column 0

row 1

row 2

Address

0000

00950

The scores variable

holds the address of a2D array of doubles.

Page 139: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-139

Accessing Two-Dimensional Array

Elements

• Programs that process two-dimensional arrays can do

so with nested loops.

• To fill the scores array:

for (int row = 0; row < 3; row++)

{

for (int col = 0; col < 4; col++)

{

System.out.print("Enter a score: ");

scores[row][col] = keyboard.nextDouble();

}

}

Number of rows, not the

largest subscript

Number of

columns, not the

largest subscript

keyboard references a

Scanner object

Page 140: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-140

Accessing Two-Dimensional Array

Elements

• To print out the scores array:

for (int row = 0; row < 3; row++)

{

for (int col = 0; col < 4; col++)

{

System.out.println(scores[row][col]);

}

}

• See example: CorpSales.java

Page 141: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-141

Initializing a Two-Dimensional Array

• Initializing a two-dimensional array requires enclosing each

row’s initialization list in its own set of braces.

int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

• Java automatically creates the array and fills its elements with

the initialization values.

– row 0 {1, 2, 3}

– row 1 {4, 5, 6}

– row 2 {7, 8, 9}

• Declares an array with three rows and three columns.

Page 142: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-142

Initializing a Two-Dimensional Array

321row 0

column 1 column 2column 0

row 1

row 2

Address

654

987

The numbers variable

holds the address of a2D array of int values.

int[][] numbers = {{1, 2, 3},

{4, 5, 6},

{7, 8, 9}};

produces:

Page 143: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-143

The length Field

• Two-dimensional arrays are arrays of one-dimensional

arrays.

• The length field of the array gives the number of rows

in the array.

• Each row has a length constant tells how many

columns is in that row.

• Each row can have a different number of columns.

Page 144: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-144

The length Field

• To access the length fields of the array:int[][] numbers = { { 1, 2, 3, 4 },

{ 5, 6, 7 },

{ 9, 10, 11, 12 } };

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

{

for (int col = 0; col < numbers[row].length; col++)

System.out.println(numbers[row][col]);

}

• See example: Lengths.java

Number of rows Number of columns in this row.

The array can have variable length rows.

Page 145: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-145

Summing The Elements of a Two-Dimensional Array

int[][] numbers = { { 1, 2, 3, 4 },

{5, 6, 7, 8},

{9, 10, 11, 12} };

int total;

total = 0;

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

{

for (int col = 0; col < numbers[row].length; col++)

total += numbers[row][col];

}

System.out.println("The total is " + total);

Page 146: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-146

Summing The Rows of a Two-Dimensional Array

int[][] numbers = {{ 1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}};

int total;

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

{

total = 0;

for (int col = 0; col < numbers[row].length; col++)

total += numbers[row][col];

System.out.println("Total of row "

+ row + " is " + total);

}

Page 147: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-147

Summing The Columns of a Two-Dimensional Array

int[][] numbers = {{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}};

int total;

for (int col = 0; col < numbers[0].length; col++)

{

total = 0;

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

total += numbers[row][col];

System.out.println("Total of column "

+ col + " is " + total);

}

Page 148: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-148

Passing and Returning Two-Dimensional

Array References

• There is no difference between passing a single or

two-dimensional array as an argument to a method.

• The method must accept a two-dimensional array

as a parameter.

• See example: Pass2Darray.java

Page 149: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-149

Ragged Arrays• When the rows of a two-dimensional array are of different

lengths, the array is known as a ragged array.

• You can create a ragged array by creating a two-dimensional array with a specific number of rows, but no columns.

int [][] ragged = new int [4][];

• Then create the individual rows.

ragged[0] = new int [3];

ragged[1] = new int [4];

ragged[2] = new int [5];

ragged[3] = new int [6];

Page 150: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-150

More Than Two Dimensions

• Java does not limit the number of dimensions that an array may

be.

• More than three dimensions is hard to visualize, but can be

useful in some programming problems.

Page 151: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-151

Selection Sort

• In a selection sort:

– The smallest value in the array is located and moved to

element 0.

– Then the next smallest value is located and moved to

element 1.

– This process continues until all of the elements have been

placed in their proper order.

– See example: SelectionSortDemo.java

Page 152: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-152

Binary Search• A binary search:

– requires an array sorted in ascending order.

– starts with the element in the middle of the array.

– If that element is the desired value, the search is over.

– Otherwise, the value in the middle element is either greater or less than the desired value

– If it is greater than the desired value, search in the first half of the array.

– Otherwise, search the last half of the array.

– Repeat as needed while adjusting start and end points of the search.

• See example: BinarySearchDemo.java

Page 153: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-153

Command-Line Arguments

• A Java program can receive arguments from the operating

system command-line.

• The main method has a header that looks like this:

public static void main(String[] args)

• The main method receives a String array as a parameter.

• The array that is passed into the args parameter comes from

the operating system command-line.

Page 154: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-154

Command-Line Arguments

• To run the example:

java CommandLine How does this work?

args[0] is assigned "How"

args[0] is assigned "does"

args[0] is assigned "this"

args[0] is assigned "work?"

• Example: CommandLine.java

• It is not required that the name of main’s

parameter array be args.

Page 155: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-155

Variable-Length Argument Lists

• Special type parameter – vararg…– Vararg parameters are actually arrays

– Examples: VarArgsDemo1.java, VarargsDemo2.java

public static int sum(int... numbers)

{

int total = 0; // Accumulator

// Add all the values in the numbers array.

for (int val : numbers)

total += val;

// Return the total.

return total;

}

Page 156: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

package TN.demo;

public class VarargsExample1 {

public static void add(int... values) {

int total = 0;

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

total = total + values[i];

}

System.out.println(“Num. of arguments: " + values.length);

System.out.println(“Total = " + total);

}

public static void main(String[] args) {

add();

add(1, 2);

add(1, 2, 3);

add(1, 2, 3, 4);

}

}

Num. of arguments: 0

Total = 0

Num. of arguments : 2

Total = 3

Num. of arguments : 3

Total = 6

Num. of arguments : 4

Total = 10

Page 157: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-157

The ArrayList Class

• Similar to an array, an ArrayList allows object storage

• Unlike an array, an ArrayList object:

– Automatically expands when a new item is added

– Automatically shrinks when items are removed

• Requires:

import java.util.ArrayList;

Page 158: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Creating an ArrayList

7-158

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

Notice the word String written inside angled

brackets <>

This specifies that the ArrayList can hold String

objects.

If we try to store any other type of object in this ArrayList,

an error will occur.

Page 159: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-159

Using an ArrayList

• To populate the ArrayList, use the add method:– nameList.add("James");

– nameList.add("Catherine");

• To get the current size, call the size method

– nameList.size(); // returns 2

Page 160: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-160

Using an ArrayList

• To access items in an ArrayList, use the get method

nameList.get(1);

In this statement 1 is the index of the item to get.

• Example: ArrayListDemo1.java

Page 161: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-161

Using an ArrayList

• The ArrayList class's toString method returns a string

representing all items in the ArrayList

System.out.println(nameList);

This statement yields :[ James, Catherine ]

• The ArrayList class's remove method removes designated

item from the ArrayListnameList.remove(1);

This statement removes the second item.

• See example: ArrayListDemo3.java

Page 162: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-162

Using an ArrayList

• The ArrayList class's add method with one argument adds new items to the end of the ArrayList

• To insert items at a location of choice, use the add method with two arguments:

nameList.add(1, "Mary");

This statement inserts the String "Mary" at index 1

• To replace an existing item, use the set method:nameList.set(1, "Becky");

This statement replaces “Mary” with “Becky”

• See example: ArrayListDemo5.java

Page 163: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-163

Using an ArrayList

• An ArrayList has a capacity, which is the number of items

it can hold without increasing its size.

• The default capacity of an ArrayList is 10 items.

• To designate a different capacity, use a parameterized

constructor:

ArrayList<String> list = new ArrayList<String>(100);

Page 164: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Using an ArrayList

• You can store any type of object in an ArrayList

7-164

ArrayList<BankAccount> accountList =

new ArrayList<BankAccount>();

This creates an ArrayList that can hold

BankAccount objects.

Page 165: Arrays and the ArrayList Class

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Using an ArrayList

7-165

// Create an ArrayList to hold BankAccount objects.

ArrayList<BankAccount> list = new ArrayList<BankAccount>();

// Add three BankAccount objects to the ArrayList.

list.add(new BankAccount(100.0));

list.add(new BankAccount(500.0));

list.add(new BankAccount(1500.0));

// Display each item.

for (int index = 0; index < list.size(); index++)

{

BankAccount account = list.get(index);

System.out.println("Account at index " + index +

"\nBalance: " + account.getBalance());

}

See: ArrayListDemo6.java

Page 166: Arrays and the ArrayList Class

Using an ArrayList

• The diamond operator

– Beginning in Java 7, you can use the <> operator

for simpler ArrayList declarations:

Java infers the type of the ArrayList object from the

variable declaration.

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

No need to specify the data type here.