Chapter6 Arrays
Chapter6 Arrays
Objectives
• After studying this chapter, Stdent 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
• Define a method that accepts an array as its
parameter and a method that returns an array
• Describe how a two-dimensional array is
implemented as an array of arrays
Array Basics
Page 3 11/2/2008
Arrays of Primitive Data Types
• Array Declaration
• Array Creation
<variable>
Variation= 1new <data type> [ <size> ]
Variation 2
• Example
double[ ] rainfall; double rainfall [ ];
rainfall rainfall
= new double[12]; = new double[12];
rainfall
0 1 2 3 4 5 6 7 8 9 10 11
This
Thisindexed
indexedexpression
expression
refers
refers to the elementatat
to the element
The index of the first rainfall[2] position
position#2
#2
position in an array is 0.
Page 5 11/2/2008
Array Processing – Sample1
double[] rainfall = new double[12];
The
Thepublic
publicconstant
constant
length
length returnsthe
returns the
double annualAverage, capacity of an array.
capacity of an array.
sum = 0.0;
rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for month " + (i+1) ) );
sum += rainfall[i];
}
Page 6 11/2/2008
Array Processing – Sample 2
double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] = "January";
The
Thesame
samepattern
pattern
monthName[1] = "February"; for the remaining
for the remaining
… ten
tenmonths.
months.
double annualAverage, sum = 0.0;
Page 7 11/2/2008
Array Processing – Sample 3
• Compute the average rainfall for each
quarter.
//assume rainfall is declared and initialized properly
Page 8 11/2/2008
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 };
number.length 4
samplingData.length 9
monthName.length 12
Page 9 11/2/2008
Variable-size Declaration
• In Java, we are not limited to fixed-size
array declaration.
• The following code prompts the user for the
size of an array and declares an array of
designated
int size;
size:
int[] number;
size= Integer.parseInt(JOptionPane.showInputDialog(null,
"Size of an array:"));
Page 10 11/2/2008
Arrays of Objects
• In Java, in addition to arrays of
primitive data types, we can declare
arrays of objects
• An array of primitive data is a powerful
tool, but an array of objects is even
more powerful.
• The use of an array of objects allows us
to model the application more cleanly
and logically.
Page 11 11/2/2008
public class Person
{
private String name;
private int age;
private char gender;
public Person()
{age=0; name=" "; gender=' ';}
}
Page 12 11/2/2008
The Person Class
• We will use Person objects to illustrate the use of
an array of objects.
Page 13 11/2/2008
Creating an Object Array - 1
Code A
A Person[ ] person;
person = new Person[20]; Only
Onlythe
thename
nameperson
personisis
declared,
declared,no
noarray
arrayisis
person[0] = new Person( ); allocated
allocatedyet.
yet.
person
State
of
Memory
After A
A is executed
Page 14 11/2/2008
Creating an Object Array - 2
Code Person[ ] person; Now
Nowthe
thearray
arrayfor
forstoring
storing
20 Person objects
20 Person objects isis
B
B person = new Person[20]; created,
created,but
butthe
thePerson
Person
objects
objects themselvesare
themselves are
person[0] = new Person( );
not yet created.
not yet created.
person
0 1 2 3 4 16 17 18 19
State
of
Memory
After B
B is executed
Page 15 11/2/2008
Creating an Object Array - 3
Code Person[ ] person; One
OnePerson
Personobject
objectisis
person = new Person[20]; created
createdand
andthe
thereference
reference
totothis
this object is placedinin
object is placed
C
C person[0] = new Person( ); position
position0.0.
person
0 1 2 3 4 16 17 18 19
State
of Person
Memory
After C
C is executed
Page 16 11/2/2008
Person Array Processing –
Sample 2
• Find the youngest and oldest persons.
int minIdx = 0; //index to the youngest person
int maxIdx = 0; //index to the oldest person
Page 17 11/2/2008
Object Deletion – Approach 1
int delIdx = 1;
Delete
DeletePerson
PersonBBby by
A
A person[delIdx] = null; setting
setting the referenceinin
the reference
position
position11totonull.
null.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA CC DD
Before A
A is executed After A
A is executed
Page 18 11/2/2008
Object Deletion – Approach 2
int delIdx = 1, last = 3; Delete
DeletePerson
PersonBBby by
setting
setting the referenceinin
the reference
A
A person[delIndex] = person[last];
position
position11totothe
thelast
last
person[last] = null; person.
person.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA DD CC
Before A
A is executed After A
A is executed
Page 19 11/2/2008
Person Array Processing –
Sample 3
• Searching for a particular person. Approach 2
Deletion is used.
int i = 0;
if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
Page 20 11/2/2008
Passing Arrays to Methods - 1
Code A
A public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);
…
At A
A before searchMinimum
arrayOne
A.
A.Local
Localvariable
variable
number
numberdoes
does not
not
exist before the
exist before the
method
methodexecution
execution
State of
Memory
Page 21 11/2/2008
Passing Arrays to Methods - 2
Code public int searchMinimum(float[]
number))
minOne { B
B
= searchMinimum(arrayOne);
…
Page 22 11/2/2008
Passing Arrays to Methods - 3
Code public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);
… C
C
}
While at C
C inside the method
arrayOne number
C.
C.The
Thearray
arrayisis
accessed
accessedvia
via
number inside
number inside
the
themethod.
method.
State of
Memory
Page 23 11/2/2008
Passing Arrays to Methods - 4
Code public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);
…
D
D
}
At D
D after searchMinimum
arrayOne number
D.
D.The
Theparameter
parameterisis
erased.
erased.TheTheargument
argument
still
still points to thesame
points to the same
object.
object.
State of
Memory
Page 24 11/2/2008