1. Trang chủ
  2. » Công Nghệ Thông Tin

Chapter 8 Arrays and the arraylist class

49 6 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Arrays and the ArrayList Class
Định dạng
Số trang 49
Dung lượng 434,54 KB
File đính kèm Chapter 8 - Arrays and the ArrayList Class.rar (399 KB)

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 8 Chapter 8 Arrays and the ArrayList Class Introduction to Arrays Employee Class 3 Contents I What is an Array? II Processing Array Elements III Passing Arrays As Arguments to Methods IV Some.

Trang 1

Chapter 8

Arrays and the

ArrayList Class

Introduction to Arrays

Trang 2

Employee Class

Trang 3

Contents

I What is an Array?

II Processing Array Elements

III Passing Arrays As Arguments to Methods

IV Some Useful Array Algorithms and Operations

V Returning Arrays from Methods

VI The Sequential Search Algorithm

Trang 4

I What is an Array?

1 One-Dimensional Arrays

2 Accessing Array Elements

3 Inputting and Outputting Array Contents

4 Java Performs Bounds Checking

5 Watch Out for Off-by-One Errors

6 Array Initialization

7 Alternate Array Declaration Notation

Trang 5

I.1 One-Dimensional Arrays

 An one-dimensional array (array) is an object

that can store a group of value, all of the same type

 Declaration of an array reference variable

numbers

int[] numbers;

 The numbers variable can reference an array of

int values.

 Creating an array of 5 int values:

number = new int[5];

Size of array

Trang 6

Element 0

0

Element 1

0

Element 2

0

Element 3

0 Element 4

Trang 7

I.1 One-Dimensional Arrays

 Examples:

 int[] numbers = new int[5];

 float[] temperatures = new float[100]; char[] letters = new char[41];

long[] units = new long[50];

double[] sizes = new double[1200];

final int NUM_ELEMENTS = 5;

int[] numbers = new int[NUM_ELEMENTS];

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

 By default, Java initializes array elements with 0.

Trang 8

I.2 Accessing Array Elements

 Each element in an array can be accessed

through a number known as a subscript.

 A subscript is used as an index to point a

specific element within an array

 The first element is assigned the subscript 0, the

second element is assigned 1, and so forth.

 Each element in an array can be used as a

variable.

int[] numbers = new int[5];

0 numbers variable

0

0 1

0 2

0 3

0 4 subscript

Trang 9

I.2 Accessing Array Elements

 Each element in the array is accessed by its

subscript

int[] numbers = new int[5];

numbers[0] = 20; numbers[1] = 25;numbers[2] = 30; numbers[3] = 35;numbers[4] = 40;

20 numbers variable

numbers[0]

25 numbers[1]

30 numbers[2]

35 numbers[3]

40 numbers[4]

Trang 10

I.3 Inputting and Outputting

Array Contents

Trang 11

I.3 Inputting and Outputting

Array Contents

Trang 12

I.4 Java Performs Bounds

Checking

 Java performs array bounds checking

 It does not allow a statement to use a subscript that

is outside the range of valid subscripts for an array.

int[] values = new int[10];

 Java will not allow a statement to use a subscript that is less than 0 or greater than 9 with this array.

 Java will display a runtime error message if a

statement that uses an invalid subscript executes.

Trang 13

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

int[] numbers = new int[100];

for(int index = 1; index <= 100; index++)

numbers[index] = 99;

 The first element, which is at subscript 0, is skipped.

 The program will crash because 100 is an invalid

subscript.

Trang 14

I.6 Array Initialization

 Java allows us to initialize an array's elements when we create the array

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

31, 31, 30, 31, 30, 31};

 Java automatically creates the array and stores the values in the initialization list in it.

 Java determines the size of the array by the number

of items in the initialization list.

 The values are stored in the array elements in the order they appear in the list.

 The first value, 31, is stored in days[0], the second value,

28, is stored in days[1], and so forth.

Trang 15

 int[] numbers, codes, scores;

 int numbers[], codes, scores;

Trang 17

Checkpoint

 8.2 What's wrong with the following array

declarations?

int[] readings = new int[-1];

double[] measurements = new double[4.5];

 8.3 What would the valid subscript values be in

a four-element array of doubles?

 8.4 What is the difference between an array's size declarator and a subscript?

 8.5 What does it mean for a subscript to be of-bounds?

Trang 18

Checkpoint

 8.6 What happens in Java when a program tries

to use a subscript that is out-of-bounds?

 8.7 What is the output of the following code?

int[] values = new int[5];

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

values[count] = count + 1;

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

System.out.println(values[count]);

 8.8 Write a statement that creates and initializes

a double array with the following values: 1.7, 6.4, 8.9, 3.1, and 9.2 How many elements are

in the array?

Trang 19

II Processing Array Elements

1 Processing Array Elements

2 Array Length

3 The Enhanced for Loop

4 Letting the User Specify an Array's Size

5 Reassigning Array Reference Variables

6 Copying Arrays

Trang 20

II.1 Processing Array Elements

 Processing array elements is no different from processing other variables

 grossPay = hours[3] * payRate;

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

++score[2];

score[4]++;

 amount[count ];

Trang 21

II.2 Array Length

 Each array in Java has a public field named

Trang 22

II.3 The Enhanced for Loop

 Java provides a specialized version of the for

loop that, in many circumstances, simplifies array processing.

for(dataType elementVariable : array)

Trang 23

II.3 The Enhanced for Loop

 When you need to access the values that are stored in an array, from the first element to the last element, the enhanced for loop is simpler

to use than the traditional for loop

 We cannot use the enhanced for loop as

Trang 24

II.3 The Enhanced for Loop

 If we need to simultaneously work with two or more arrays within the loop

 If we need to refer to the subscript number of a

particular element

Trang 25

II.4 Letting the User Specify an

Array's Size

 Java allows us to use an integer variable to

specify an array's size declarator

 This makes it possible to allow the user to specify

an array's size.

Trang 26

26

Trang 27

II.5 Reassigning Array Reference

Variables

 It is possible to reassign an array reference

variable to a different array

//Create an array referenced by the numbers variable int[] numbers = new int[10];

//Reassign numbers to a new array.

numbers = new int[5];

address

The numbers variables

holds the address of an int array

The ten-element int array previously referenced

A five-element int array

Trang 28

II.6 Copying Arrays

 An array is an object An array and a reference variable are two separate entities

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

int[] array2 = array1;

 This does not copy array1.

 Both array1 and array2 reference the same array.

An int array address

The array1 variable holds

the address of an int array.

address The array2 variable holds

the address of an int array.

Trang 29

II.6 Copying Arrays

 To copy an array we need to copy the individual elements of one array to another

 Usually, this is best done with a loop, such as the following:

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

int[] secondArray = new int[5];

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

secondArray[index] = firstArray[index];

Trang 30

 Write a statement that multiplies element 0 of the

numbers1 array by element 3 of the numbers2

array and assigns the result to the result variable.

 8.10 A program uses a variable named arraythat references an array of integers We do not know the number of elements in the array Write

a for loop that stores -1 in each element of the array

Trang 31

Checkpoint

 8.11 A program has the following declaration:

double[] values;

 Write code that asks the user for the size of the

array and then creates an array of the specified

size, referenced by the values variables.

 8.12 Look at the following statememts:

int[] a = {1, 2, 3, 4, 5, 6, 7};int[] b = new int[7];

 Write code that copies the a array to the b array.

Trang 32

III Passing Arrays As Arguments

to Methods

 To pass an array, we pass the value in the

variable that references the array

 It is passed just as an object is passed:

 The actual array itself is not passed, but the

reference to the array is passed into the parameter.

 This means the method has direct access to the

original array.

Trang 33

III Passing Arrays As Arguments

to Methods

showArray(numbers);

public static void showArray(int[] array) {

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

Trang 34

34

Trang 36

IV Some Useful Array Algorithms

and Operations

1 Comparing Arrays

2 Summing the Values in a Numeric Array

3 Getting the Average of the Values in a Numeric Array

4 Finding the Highest and Lowest Values in a

Numeric Array

5 Partially Filled Arrays

6 Working with Arrays and Files

Trang 37

IV.1 Comparing Arrays

 To compare the contents of two arrays, we must compare the elements of the two arrays

 We cannot use the == operator to compare two array reference variables and determine the

arrays are equal

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

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

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

Trang 38

IV.1 Comparing Arrays

 Comparing the contents of two arrays:

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

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

boolean arrayEqual = true; //Flag variable

int index = 0; //Loop control variable

//First determine whether the arrays are the same size.

Trang 39

int acc = 0; // Initialize accumulator

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

acc += units[index];

Trang 40

IV.3 Getting the Average of the

Values in a Numeric Array

 The first step in calculating the average of all

the values in an array is to sum the values

 The second step is to divide the sum by the

number of elements in the array

double[] scores = new double[10];

//

double acc = 0; // Initialize accumulator

double average; //Will hold the average

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

acc += scores[index];

average = acc / scores.length;

Trang 41

IV.4 Finding the Highest and

Lowest Values in a Numeric Array

int[] numbers = new int[50];

//

//Find the highest value

int highest = numbers[0];

for(int index = 1; index < numbers.length;

Trang 42

IV.5 Partially Filled Arrays

 Sometimes we need to store a series of items in an

array, but we do not know the number of items that

 A partially filled array is normally used with an

accompanying integer variable that holds the number of items stored in the array.

Trang 43

 Use a loop to step through each element of the

array, writing its contents to the file.

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

//Open the file

FileWriter fwriter = new FileWriter(“Values.txt”);

PrintWriter outputFile = new PrintWriter(fwriter);

//Write the array elements to the file

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

outputFile.println(numbers[index]);

//Close the file

outputFile.close();

Trang 44

IV.6 Working with Arrays and

Files

Open the file Values.txt and read its contents back

into the numbers array:

int[] number = new int[5];

String str; // To hold lines read from the file int index = 0; // Loop control variable

//Open the file

FileReader freader = new FileReader(“Values.txt”);

BufferedReader inputFile = new

BufferedReader(freader);

Trang 46

V Returning Arrays from

Methods

 A method can return a reference to an array

 The return type must be an array reference.

public static double[] getArray()

Trang 47

VI The Sequential Search

Algorithm

 A search algorithm is a method of locating a

specific item in a large collection of data

 The sequential search algorithm uses a loop to sequentially steps through an array:

 Starts with the first element.

 Compares each element with the value being

Trang 48

48

Ngày đăng: 27/09/2022, 22:24

TỪ KHÓA LIÊN QUAN