Tải bản đầy đủ (.pdf) (49 trang)

Chapter 8 Arrays and the arraylist class

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (434.54 KB, 49 trang )

Chapter 8

Arrays and the
ArrayList Class
Introduction to Arrays


Employee Class


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

3


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
4



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.
Size of array

Creating an array of 5 int values:
number = new int[5];

5


I.1. One-Dimensional Arrays
Enough memory
to hold one int


int count;

1234
Enough memory
to hold one double

double number;

1234.55
Enough memory
to hold one char

char letter;

A

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

numbers variable

Element

0

Element

0


Element

0

0

Element
3

6
Element
4


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.

7


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

0

0

0

0

numbers variable

8
subscript

0

1

2

3

4


I.2. Accessing Array Elements



Each element in the array is accessed by its
subscript.

int[] numbers = new int[5];
numbers[0] = 20;
numbers[2] = 30;
numbers[4] = 40;
20

numbers[1] = 25;
numbers[3] = 35;
25

30

35

40

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

9


I.3. Inputting and Outputting
Array Contents

10



I.3. Inputting and Outputting
Array Contents

11


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



I.5. Watch Out for Off-by-One
Errors


Because array subscript start at 0 rather than 1,
you have to careful not to perform an off-by-one
error.

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

13


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,
14
28, is stored in days[1], and so forth.


I.7. Alternate Array Declaration
Notation


Java allows us to use two different styles when
declaring array reference variables.







int[] numbers;
int numbers[];

The difference between the two styles is notices
when more than one variable is declared in the
same statement.




int[] numbers, codes, scores;
int numbers[], codes, scores;
15


Checkpoint


8.1 Write a statements that create the following
arrays”







a. A 100-element int array referenced by the
variable employeeNumbers.
b. A 25-element double array referenced by the
variable payRates.
c. A 14-element float array referenced by the
variable miles.

16


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 out17

of-bounds?


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 18
in the array?


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

19


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

20


II.2. Array Length





Each array in Java has a public field named
length.

This field contains the number of elements in
the array.

double[] temperatures = new double[25];
...

for(int i = 0; i < temperatures.length; i++)
System.out.println(temperatures[i]);



The largest subscript in an array is length-1.
21


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




For example:


int[] numbers = { 3, 6, 9 };
for(int val : numbers)
System.out.println(val);
22


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
follows:






If we need to change the contents of an array

element
If we need to work through the array elements in
reverse order
If we need to access some of the array elements,
but not all of them

23


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

24


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.

25


×