Title: Arrays
1Arrays
- Chapter 8
- Dr. James Jiang
Arrays
2Array
List of data items that have the same name and
the same data type
declare array variable
reserve memory
double salesFigure
salesFigure new double20
3double salesFigure new double20
- Reserves 20 memory locations for 20 salesFigures
- Subscript integer reference to an array
variable (element) - Examples
- salesFigure0 2100.00
- System.out.println(salesFigure19)
4Initializing an Array
- Array element holds a memory address where a
value is stored (p. 202) - Use list of values, separated by commas, enclosed
in curly brackets - int tenMult 10, 20, 30, 40, 50, 60
- Keyword new not required
- Size assigned based on number of values
5Initialization
double salary new double4 salary0
5.25 salary1 6.55 salary2
10.25 salary3 16.85
OR
double salary 5.25, 6.55, 10.25, 16.85
6Using Subscripts with an Array
- Use a variable as the subscript
- salarysub 3.0
- Example
- for(sub 0 sub lt 4 sub)
- salarysub 3.0
- salary
- 01 23
8.25
9.55
13.25
19.85
7Using the for loop with arrays
for(int x 0 x lt 4 x) System.out.println(
salaryx)
Initialize and vary the subscript
8Declaring an Array of Objects
- An array of Employees
- Call 7 different constructors
Employee emp new Employee7
For(x 0 x lt 7 x) empx new
Employee(101 x, 5.35)
Employee(int num, double sal) empNum num
empSalary sal
The constructor
9For(x 0 x lt 7 x) empx new
Employee(101 x, 5.35)
- emp0 emp1 emp2 emp3 emp4 emp5 emp6
- 101 102 103 104 105 106 107
- 5.35 5.35 5.35 5.35 5.35 5.35 5.35
Employee(int num, double sal) empNum num
empSalary sal
The constructor
10Using an array object method
For(x 0 x lt 7 x) System.out.println
(empx.getEmpNum() empx.getSalary())
The method belongs to a particular emp
11Searching an Array for an Exact Match
- Initialize array with valid values
- Examine the array for a match
int validValues 101, 108, 201, 213, 266,
304, 311, 409, 411, 412
What is a parallel array?
for(int x 0 x lt 10 x) if(itemOrdered
validValuesx) validItem true
12Parallel Arrays
int validValues 101, 108, 201, 213, 266,
304, 311, 409, 411, 412
double prices 0.89, 1.23, 3.50, 0.69, 5.79,
3.19, 0.99, 0.89, 1.26, 8.00
- for(int x 0 x lt 10 x)
-
- if(itemOrdered validValuesx)
-
- validItem true
- itemPrice pricesx
- x 10 // Break out of loop when match
-
13Using the while loop to search
14Searching an Array - Range match
See Figure 8-7, p. 247
15Passing Arrays to Methods
for(x 0 x lt 4 x) methodGetsOneInt(someNums
x)
Only a copy of someNumsx is passed not the
actual variable
int someNums 5, 10, 15, 20 methodGetsArray
(someNums)
Arrays are passed by reference the
actual variables are NOT changed
16Using the Array Length
- Every array object automatically assigned data
field --gt length - salaries.length contains the value 8
double salaries new double8
for(x 0 x lt salaries.length x) ...