Java 02 Array
Java 02 Array
Objectives
After you have read and studied this chapter, you
should be able to
Array Basics
An array is a collection of data values.
If your program needs to deal with 100
integers, 500 Account objects, 365 real
numbers, etc., you will use an array.
In Java, an array is an indexed collection of
data values of the same type.
3
//variation 1
//variation 2
Array Creation
<variable>
Example
Variation 2
Variation 1
double[ ] rainfall;
rainfall
= new double[12];
double rainfall [ ];
rainfall
= new double[12];
rainfall
rainfall[2]
10
11
This
Thisindexed
indexedexpression
expression
refers
to
the
element
refers to the elementatat
position
position#2
#2
annualAverage,
sum = 0.0;
The
Thepublic
publicconstant
constant
length
returns
length returnsthe
the
capacity
of
an
array.
capacity of an array.
Sample 1
import java.io.*;
class Rain
{
public static void main(String[] arg) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(read);
double [] rainFall = new double[12];
double anualAverage, sum=0;
for (int i=0; i<rainFall.length; i++)
{
System.out.print("Rainfall for month "+(i+1)+"=");
rainFall[i] = Double.parseDouble(input.readLine());
sum += rainFall[i];
}
anualAverage = sum / rainFall.length;
System.out.println("Average is = "+anualAverage);
}
}
double
The
Thesame
samepattern
pattern
for
the
remaining
for the remaining
ten
tenmonths.
months.
The
Theactual
actualmonth
month
name
instead
name insteadofofaa
number.
number.
Sample 2
import java.io.*;
class Rain
{
public static void main(String[] arg) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(read);
double [] rainFall = new double[2];
String [] monthName = new String[2];
monthName[0] ="January";
monthName[1] ="February";
double anualAverage, sum=0;
for (int i=0; i<rainFall.length; i++)
{
System.out.print("Rainfall for "+monthName[i]+ "=");
rainFall[i] = Double.parseDouble(input.readLine());
sum += rainFall[i];
}
anualAverage = sum / rainFall.length;
System.out.println("Average is = "+anualAverage);
}
}
}
quarterAverage[i] = sum / 3.0;
10
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" };
number.length
samplingData.length
monthName.length
4
9
12
11
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 size:
int size;
int[] number;
System.out.print(Size of an array = )
size= Integer.parseInt(input.readLine());
number = new int[size];
12
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.
13
14
15
Person latte;
The
ThePerson
Personclass
class
supports
the
set
supports the setmethods
methods
and
get
methods.
and get methods.
);
);
16
A
A
Person[ ]
person;
Only
Onlythe
thename
nameperson
person
isisdeclared,
no
array
declared, no arrayisis
allocated
allocatedyet.
yet.
person
State
of
Memor
y
After A
A is executed
17
Person[ ]
B
B
person;
Now
Nowthe
thearray
arrayfor
forstoring
storing
20
Person
objects
is
20 Person objects is
created,
created,but
butthe
thePerson
Person
objects
themselves
objects themselvesare
are
not
yet
created.
not yet created.
person
0
State
of
Memor
y
16 17 18 19
After B
B is executed
18
Person[ ]
person;
C
C
One
OnePerson
Personobject
objectisis
created
createdand
andthe
thereference
reference
totothis
object
is
placed
this object is placedinin
position
position0.0.
person
0
State
of
Memor
y
16 17 18 19
Person
After C
C is executed
19
20
Class Person
Class Person
{
public Person(String newName, int newAge, char newGender)
{
name = newName;
age = newAge;
gender = newGender;
}
21
22
23
String
name, inpStr;
int
age;
char
gender;
= inputBox.getString("Enter name:");
age
= inputBox.getInteger("Enter age:");
person[i].setName
( name
);
person[i].setAge
);
age
person[i].setGender( gender );
}
24
minIdx = 0;
int
maxIdx = 0;
= i;
= i;
}
}
//person[minIdx] is the youngest and person[maxIdx] is the oldest
25
A
A
person
person
0
AA
Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totonull.
null.
person[delIdx] = null;
BB
CC
D
D
Before A
A is executed
AA
CC
D
D
After A
A is executed
26
A
A
person[last]
person
= null;
person
0
AA
Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totothe
thelast
last
person.
person.
person[delIndex] = person[last];
BB
CC
D
D
Before A
A is executed
AA
D
D
CC
After A
A is executed
27
int i = 0;
while ( person[i] != null && !person[i].getName().equals("Latte") ) {
i++;
}
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);
}
28
A
A
minOne
= searchMinimum(arrayOne);
At
A
A before searchMinimum
arrayOne
A.
A.Local
Localvariable
variable
State
of
Memor
y
number
numberdoes
does not
not
exist
before
the
exist before the
method
methodexecution
execution
29
B
B
number
B.
B.The
Thevalue
valueofofthe
the
State
of
Memor
y
argument,
argument,which
whichisis
an
anaddress,
address,isis
copied
copiedtotothe
the
parameter.
parameter.
30
C
C
While at C
C inside the method
arrayOne
State
of
Memor
y
number
C.
C.The
Thearray
arrayisis
accessed
accessedvia
via
number
inside
number inside
the
themethod.
method.
31
D
D
}
At D
D after searchMinimum
arrayOne
number
D.
D.The
Theparameter
parameterisis
State
of
Memor
y
erased.
erased.The
Theargument
argument
still
points
to
the
still points to thesame
same
object.
object.
32
Two-Dimensional Arrays
Two-dimensional arrays are useful in representing tabular information.
33
//variation 1
//variation 2
Creation
<variable>
Example
double[][] payScaleTable;
payScaleTable
= new double[4][5];
0
1
2
3
34
Accessing an Element
An element in a two-dimensional array is
accessed by its row and column index.
35
36
=
=
=
=
new
new
new
new
double
double
double
double
[5];
[5];
[5];
[5];
38
Array Applications
Searching Arrays
Searching is the process of looking for a
specific element in an array; for example,
discovering whether a certain score is included
in a list of scores. Searching, like sorting, is a
common task in computer programming. There
are many algorithms and data structures
devoted to searching. In this section, two
commonly used approaches are discussed,
linear search and binary search.
39
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in
the array list. The method continues to do so
until the key matches an element in the list or the
list is exhausted without a match being found. If
a match is made, the linear search returns the
index of the element in the array that matches the
key. If no match is found, the search returns -1.
40
41
Binary Search
For binary search to work, the elements in
the array must already be ordered. Without
loss of generality, assume that the array is
in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key
with the element in the middle of the array.
Consider the following three cases:
42
low
key < 50
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list
2
low
key > 7
mid
7 10 11 45
mid
high
50 59 60 66 69 70 79
high
mid
high
list
10 11 45
44
45
46
For the binarySearch method to work, the array must be pre-sorted in increasing
order.
47
Recursive Implementation
/** Use binary search to find the key in the list */
public static int recursiveBinarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
return recursiveBinarySearch(list, key, low, high);
}
/** Use binary search to find the key in the list between
list[low] list[high] */
public static int recursiveBinarySearch(int[] list, int key,
int low, int high) {
if (low > high) // The list has been exhausted without a match
return -low - 1;
int mid = (low + high) / 2;
if (key < list[mid])
return recursiveBinarySearch(list, key, low, mid - 1);
else if (key == list[mid])
return mid;
else
return recursiveBinarySearch(list, key, mid + 1, high);
}
48
References
Thomas Wu. C, An Introduction To Object-
49