? 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 1
Chapter 9
Arrays
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 2
Chapter 9 Objectives
After you have read and studied this chapter,you should be able to
Manipulate a collection of data values using an array.
Declare and use an array of primitive data types in writing a
program.
Declare and use an array of objects in writing a program.
Describe how a two-dimensional array is implemented as an
array of arrays.
Manipulate a collection of objects using a vector.
Use a MultiInputBox object from the javabook package to input
an array of strings.
Define a method that accepts an array as its parameter and a
method that returns an array.
Describe how the self-reference pointer works and use it in
methods.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 3
Array Basics
Suppose you need to handle up to 300 Student objects in a program for maintaining a high school
alumni list,would you use 300 variables?
Suppose you need to process daily temperatures for a 12-month period in a science project,would you use
365 variables?
You can,but would you?
An array is a collection of data values of the same data type,
If your program needs to deal with 100 integers,500 Account objects,365 real numbers,etc.,you will use
an array.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 4
Arrays of Primitive Data Types
Array Declaration
<data type> [ ] <variable> //variation 1
<data type> <variable>[ ] //variation 2
Array Creation
<variable> = new <data type> [ <size> ]
Example
double[ ] rainfall;
rainfall
= new double[12];
Variation 1
double rainfall [ ];
rainfall
= new double[12];
Variation 2
An array is like an object!
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 5
Accessing Individual Elements
Individual elements in an array accessed with the
indexed expression.
double[] rainfall = new double[12];
rainfall 0 1 2 3 4 5 6 7 8 9 10 11
rainfall[2]
This indexed expression
refers to the element at
position #2
The index of the first
position in an array is 0.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 6
Array Processing – 1
double[] rainfall = new double[12];
double annualAverage,
sum = 0.0;
for (int i = 0; i < rainfall.length; i++) {
rainfall[i] = inputBox.getDouble("Rainfall for month "
+ (i+1) );
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
The public constant
length returns the
capacity of an array.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 7
Array Processing – 2
double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] =,January”;
monthName[1] =,February”;

double annualAverage,sum = 0.0;
for (int i = 0; i < rainfall.length; i++) {
rainfall[i] = inputBox.getDouble("Rainfall for month "
+ monthName[i] );
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
The same pattern
for the remaining
ten months.
The actual month
name instead of a
number.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 8
Array Processing – 3
Compute the average rainfall for each quarter.
//assume rainfall is declared and initialized properly
double[] quarterAverage = new double[4];
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 3; j++) {
//compute the sum of
sum += rainfall[3*i + j]; //one quarter
}
quarterAverage[i] = sum / 3.0; //Quarter (i+1) average
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 9
Array Initialization
Like other data types,it is possible to declare and
initialize an array at the same time.
int[] number = { 2,4,6,8 };
double[] samplingData = { 2.443,8.99,12.3,45.009,18.2,
9.00,3.123,22.084,18.08 };
String[] monthName = {"January","February","March",
"April","May","June","July",
"August","September","October",
"November","December" };
The capacity of the array is set to the number of
elements in the list.
number.length
samplingData.length
monthName.length
4
9
12
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 10
Arrays of Objects
An array of primitive data is a powerful tool,but even
more powerful is an array of objects.
By combining the power of arrays and objects,we
can structure programs in a clean and logical
organization.
If we have only arrays of primitives,then to
represent a collection of Person or Account objects,
for example,we need to use several different arrays,one for names,one for addresses,and so forth,This
is very cumbersome and error-prone,
An array of Person objects or an array of Account
objects will result in a more concise and easier-to-
understand code.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 11
The Person Class
We will use Person objects to illustrate the use of an
array of objects.
Person latte;
latte = new Person( );
latte.setName("Ms,Latte");
latte.setAge(20);
latte.setGender('F');
outputBox.printLine( "Name," + latte.getName() );
outputBox.printLine( "Age," + latte.getAge() );
outputBox.printLine( "Sex," + latte.getGender() );
The Personclass
supports the set methods
and get methods.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 12
Creating an Array of Person Objects - 1
Code
State
of
Memory
Person[ ] person;
person = new Person[20];
person[0] = new Person( );
A
Only the name person is
declared,no array is
allocated yet.
After is executedA
person
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 13
person
Creating an Array of Person Objects - 2
Code
State
of
Memory
Person[ ] person;
person = new Person[20];
person[0] = new Person( );
B
Now the array for storing
20 Person objects is
created,but the Person
objects themselves are
not yet created.
After is executedB
0 1 2 3 4 16 17 18 19
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 14
Creating an Array of Person Objects - 3
Code
State
of
Memory
Person[ ] person;
person = new Person[20];
person[0] = new Person( );C
One Personobject is
created and the reference
to this object is placed in
position 0.
0 1 2 3 4 16 17 18 19
person
After is executedC
Person
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 15
Person Array Processing - 1
Create Person objects and set up the person array,
String name,inpStr;
int age;
char gender;
for (int i = 0; i < person.length; i++) {
name = inputBox.getString("Enter name:"); //read in data values
age = inputBox.getInteger("Enter age:");
inpStr = inputBox.getString("Enter gender:");
gender = inpStr.charAt(0);
person[i] = new Person( ); //create a new Person and assign values
person[i].setName ( name );
person[i].setAge ( age );
person[i].setGender( gender );
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 16
Person Array Processing - 2
Find the average age of 18-year-old males,
float sum = 0,averageAge;
int count = 0;
for (int i = 0; i < person.length; i++) {
if ( person[i].getAge( ) = 18 &&
person[i].getGender{ } =?M? ) {
sum += person[i].getAge();
}
}
averageAge = sum / count;
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 17
Person Array Processing - 3
Find the youngest and oldest persons,
int minIdx = 0; //index to the youngest person
int maxIdx = 0; //index to the oldest person
for (int i = 1; i < person.length; i++) {
if ( person[i].getAge() < person[minIdx].getAge() ) {
minIdx = i; //found a younger person
}
else if (person[i].getAge() > person[maxIdx.getAge() ) {
maxIdx = i; //found an older person
}
}
//person[minIdx] is the youngest and person[maxIdx] is the oldest
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 18
Object Deletion – Approach 1
int delIdx = 1;
person[delIdx] = null
Delete Person B by
setting the reference in
position 1 to null.
0 1 2 3
person
A B C D
A
0 1 2 3
person
A C D
Before is executedA After is executedA
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 19
Object Deletion – Approach 2
int delIdx = 1,last = 3;
person[delIndex] = person[last];
person[last] = null;
Delete Person B by
setting the reference in
position 1 to the last
person.
0 1 2 3
person
A B C D
A
0 1 2 3
person
A CD
Before is executedA After is executedA
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 20
Person Array Processing - 4
Searching for a particular person,Approach 2 Deletion is used,
int i = 0;
while ( person[i] != null && !person[i].getName().equals("Latte") ) {
i++;
}
if ( person[i] == null ) {
//not found - unsuccessful search
outputBox.printLine("Ms,Latte was not in the array");
}
else {
//found - successful search
outputBox.printLine("Found Ms,Latte at position " + i);
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 21
Passing Arrays to Methods - 1
Code
State of
Memory
minOne
= searchMinimum(arrayOne);
public int searchMinimum(float[]
number))
{

}
A
At before searchMinimumA
arrayOne
A,Local variable
number does not
exist before the
method execution
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 22
Passing Arrays to Methods - 2
Code
State of
Memory
minOne
= searchMinimum(arrayOne);
public int searchMinimum(float[]
number))
{

}
arrayOne
B
The address is copied at B
number B,The value of the
argument,which is
an address,is copied
to the parameter.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 23
arrayOne number
While at inside the methodC
Passing Arrays to Methods - 3
Code
State of
Memory
minOne
= searchMinimum(arrayOne);
public int searchMinimum(float[]
number))
{

}
C
C,The array is
accessed via
number inside
the method.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 24
arrayOne number
Passing Arrays to Methods - 4
Code
State of
Memory
minOne
= searchMinimum(arrayOne);
public int searchMinimum(float[]
number))
{

}
D
At after searchMinimumD
D,The parameter is
erased,The argument
still points to the same
object.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 25
MultiInputBox
The MultiInputBox class is used accept multiple input
values,
String[] label = {“Name”,“Address”,“Phone Number”};
MultiInputBox multiBox = new MultiInputBox( mainWindow,3 );
multiBox.setLabels( label );
multiBox.setTitle(“Input for a Bank”);
String[] answer = multiBox.getInputs( );
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 26
MultiInputBox - getInputs
The getInputs method returns an array of String
objects.
String[] answer = multiBox.getInputs( );
answer
0 1 2
String
Java Joe
String
1 First St.
String
19
NOTE,This is a
String value,not a
numerical value,
You need to
convert it to a
numerical value.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 27
MultiInputBox Methods
CLASS,MultiInputBox
Method Argument Description
<constructor>
MainWindow,
int
Creates a MultiInputBox object,The second
argument specifies the number of labels.
<constructor>
MainWindow,
array of String
Creates a MultiInputBox object,The second
argument is an array of String for labels.
setLabels array of String Sets the labels of a MultiInputBox object to the passed array of String.
getInputs <none> Returns an array of String entered by the user.
See the complete documentation for more details.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 28
Self-Referencing Pointer
The reserved word this is used to refer explicitly to an object’s data members and methods from the
object’s method.
Up till now,the reserved word this was not used because there were no conflicts.
class Tester
{
public void m1( )
{
}
public void m2( )
{
m1( );
}
}
class Tester
{
public void m1( )
{
}
public void m2( )
{
this.m1( );
}
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 29
Local vs,Data Member Reference
What does the identifier age refer to?
class Person
{
int age;
...
public void setAge( int age )
{
..,age,..
}
}
class Person
{
int age;
...
public void setAge( int pAge )
{
..,age,..
}
}There’s a matching
parameter declaration locally,
so age refers to the
parameter
There’s no matching
parameter declaration locally,
so age refers to the data
member.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 30
Avoiding Naming Conflict with this
class Person
{
int age;
...
public void setAge( int age )
{
this.age = age ;
}
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 31
Calling a Constructor Using this
The reserved word this is used in a special syntax
when calling a constructor from another constructor
of the same class.
class Person
{
public void Person( )
{
this(,Not Given”,0,?U? );
}
public void Person( String name,int age,char gender )
{
this.name = name;
this.age = age;
this.gender = gender;
}

}
This class has two constructors,
The first constructor calls the
second with default values for
arguments.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 32
Sample Development,AddressBook
Problem Statement
Write an AddressBook class that manages a collection
of Person objects,An AddressBook object will allow the
programmer to add,delete,or search for a Person
object in the address book.
Overall Design
Method Description
<constructor> A constructor to initialize the object,We will include multiple constructors as necessary.
add Adds a new Person object to the address book.
delete Deletes a specified Person object from the address book.
search Searches a specified Person object in the address book and returns this person if found.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 33
AddressBook – Development Steps
1,Implement the constructor(s).
2,Implement the add method.
3,Implement the search method.
4,Implement the delete method.
5,Finalize the class
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 34
Two-Dimensional Arrays
Two-dimensional arrays are useful in representing
tabular information.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 35
Declaring and Creating a 2-D Array
Declaration
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2
Creation
<variable> = new <data type> [ <size1> ][ <size2> ]
Example
double[][] payScaleTable;
payScaleTable
= new double[4][5];
3
2
1
0
43210
payScaleTable
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 36
Sample 2-D Array Processing
Find the average of each row,
double[ ] average = { 0.0,0.0,0.0,0.0 };
for (int i = 0; i < payScaleTable.length; i++) {
for (int j = 0; j < payScaleTable[i].length; j++) {
average[i] += payScaleTable[i][j];
}
average[i] = average[i] / payScaleTable[i].length;
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 37
Vectors
The Vector class,defined in the standard java.util
package,implements an expandable array of objects.
We can keep on adding more elements to a Vector
without worrying about overflowing its storage
capacity,
Internally,the Vector class maintains an array of
objects,and when the overflow condition occurs,its
array is replaced with a bigger array,similar to the way the expand method of the AddressBook class
handles the overflow.
Vector elements must be objects; they cannot be
primitive data values such as int and double.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 38
Vector Processing - 1
Create a vector named friends and add two Person
objects.
import java.util.*;
Vector friends;
Person person;
friends = new Vector( );
person = new Person("jill",10,'F');
friends.add( person );
person = new Person("jack",6,'M');
friends.add( person );
The Vector class is
defined in this
package.
This creates a new
vector with a default
capacity 10.
Adds a new Person
to the end.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 39
Vector Processing - 2
Prints out the name of all Person objects in the
friends vector.
Person p;
int limit = friends.size( );
for (int i = 0; i < limit; i++ ) {
p = (Person) friends.elementAt( i );
System.out.println( p.getName( ) );
}
The size method
returns the number of
objects in the vector.
This elementAt
method returns the
object at position i.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 9 - 40
Vector Processing - 3
To store primitive data values in a vector,we need to
use the wrapper classes Integer,Double,etc.
Vector intVector = new Vector( );
intVector.add( new Integer( 15 ) );
intVector.add( new Integer( 30 ) );
...
Integer intObject;
Enumeration enum = intVector.elements( );
while ( enum.hasMoreElements( ) ) {
intObject = (Integer) enum.nextElement( );
System.out.println( intObject.intValue( ) );
}
The intValue
method of the
Integer class
returns the integer
value as primitive
data type int.
The End