You are on page 1of 84

Chapter 10

Arrays

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 10 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.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 10 Objectives, cont.


After you have read and studied this
chapter, you should be able to
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.
Manipulate a collection of objects, using
lists and maps.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


In Java, an array is an indexed
collection of data values of the same
type.
Arrays are useful for sorting and
manipulating a collection of values.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.1
Sample array: Monthly rainfall averages
and their variation from the annual
average.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


Square brackets [] are used to declare
an array.
To declare an array, we may attach the
brackets to either the data type or the
variable name.
An array named rainfall of type
double, may be stated either as
double [] rainfall;
or
double rainfall [];
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


In Java, an array is a reference data
type.
We use the new operator to allocate the
memory to store the values in an
array.
rainfall = new double [12];
//creates an array of size 12.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.2
An array of 12 double values.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


We use a single identifier to refer to the
whole collection in the array.
We use an indexed expression to refer
to the individual values of the
collection. Arrays use zero-based
indexing.

An individual value in an array is called


an array element.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.3
An array of 12 double values after all
12 are assigned values.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


An array has a public constant length
for the size of an array.
for (i=0; i<rainfall.length; i++){
...
}

This approach is particularly useful


when the size of an array may change,
or is not known in advance.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


Do not confuse the length value of an
array and the length method of a
String object.
The length is a method for a String
object, so we use the syntax for calling
a method.
String str = This is a string;
int size = str.length();

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


An array, on the other hand, is a
reference data type, not an object.
Therefore, we do not use a method
call.
int size = rainfall.length;

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


We can initialize the array at the time it
is declared:
String[] monthName = { January,
February, March, April, May,
June, July, August, September,
October, November, December };

Because the array is initialized here, it is


unnecessary to state the size of the
array. The size is determined by the
number of values in the list.
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


Using constants to declare the array
sizes does not always lead to efficient
use of space.
Declaration of arrays with constants is
called fixed-size array declaration.
Fixed-size array declaration may pose
two problems:
Not enough capacity for the task at hand.
Wasted space.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


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;
size= Integer.parseInt(
JOptionPane.showInputDialog(null,
Size of an array:));
number = new int[size];

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.1 Array Basics


Any valid integer arithmetic expression is
allowed for specifying the size of an
array:
size = Integer.parseInt(
JOptionPane.showInputDialog(null,));
number = new int[size*size + 2* size + 5];

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


Arrays are not limited to primitive data
types.
We will use the Person class to
illustrate this concept.
An array of objects is declared and
created just as an array of primitive
data types is.
Person[] person;
person = new Person[20];

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.4
An array of Person objects after the
array is created.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


Array elements are initially null.

Since each array element is an object,


each must also be created.
person[0] = new Person( );

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.5
The person array with one Person
object added to it.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


To assign data values to this object, we
can execute
person[0].setName (Ms. Latte);
person[0].setAge (20);
person[0].setGender (F);

The syntax here is the one used to call


an objects method; we are using an
indexed expression to refer to the
object instead of a simple variable.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


The following program illustrates
various aspects of array processing:
Creating a new person array.
Creating a new Person object and
assigning values to it.
Finding the average age of the persons in
the array.
Finding the youngest and oldest persons
in the array.
Finding a particular person in the array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


/*
Chapter 10 Sample Program: Illustrate the
processing of an array of Person objects

File: Ch10ProcessPersonArray.java
*/
import javax.swing.*;

class Ch10ProcessPersonArray {
public static void main (String[] args) {
Person[]
person; //declare the person array
person = new Person[5];
//and then create it

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


//----------- Create person Array ------------//
String
name, inpStr;
int
age;
char
gender;
for (int i = 0; i < person.length; i++) {
//read in data values
name = JOptionPane.showInputDialog(null,
"Enter name:");
age = Integer.parseInt(
JOptionPane.showInputDialog(null,
"Enter age:"));

inpStr =JOptionPane.showInputDialog(null,
"Enter gender:");
gender = inpStr.charAt(0);

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


//create a new Person and assign values
person[i] = new Person( );
person[i].setName ( name
);
person[i].setAge
( age
);
person[i].setGender( gender );
}
//------ Compute Average Age --------------//
float sum = 0, averageAge;
for (int i = 0; i < person.length; i++) {
sum += person[i].getAge();
}
averageAge = sum / (float) person.length;
System.out.println("Average age: " +
averageAge);
System.out.println("\n");

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


//-- Find the youngest and oldest person ------//
//-- Approach No. 3: Using person reference ---//
Person youngest, //points to the youngest person
oldest;
//points to the oldest person
youngest = oldest = person[0];
for (int i = 1; i < person.length; i++) {
if ( person[i].getAge() < youngest.getAge() ) {
//found a younger person
youngest
= person[i];
}
else if (person[i].getAge() > oldest.getAge() ) {
//found an older person
oldest
= person[i];
}
}
System.out.println("Oldest : " + oldest.getName()
+ " is " + oldest.getAge() + " years old.");
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


System.out.println("Youngest: " +
youngest.getName() + " is " +
youngest.getAge() + " years old.");

//----- Search for a particular person ------//


String searchName =
JOptionPane.showInputDialog(null,
"Name to search:");
int i = 0;
while ( i < person.length &&
//still more persons to search
!person[i].getName().equals( searchName ) ) {
i++;
}

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


if (i == person.length) {
//not found - unsuccessful search
System.out.println( searchName + "
was not in the array" );
} else {
//found - successful search
System.out.println("Found " +
searchName + " at position "
+ i);
}
}
}

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.6
An array of Person objects with two
Person variables.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


Deleting objects from an array requires
us to search for the Person object to
be removed.
When the object is located, there are
two ways to delete the object.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


The first approach is to set the array
element to null.
Because each array element is a
reference to an object, setting the
element to null accomplishes this task
easily.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.7
Approach 1 deletion: Setting a reference to
null. The array length is 4.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


Any index position may be set to null,
but this approach creates holes in
the array.
The second approach to deleting an
object will order the elements so the
real references occur at the beginning
and the null references at the end.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


Packing the elements so the real
references occur at the beginning and the
null references occur at the end.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


We must fill the holes. There are two
possible approaches:
If an object at position J is removed (i.e.,
set to null), then elements from position
J+1 up to the last non-null reference are
shifted one position lower. Finally, the last
non-null reference is set to null.
Replace the removed element by the last
element in the array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.8
Approach 2 deletion: Replace the removed
element with the last element in the array.
The array length is 4.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


Note that assigning null to an array
element will not erase the object.
This operation does initiate a chain
reaction that will eventually erase the
object from memory.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


A single object may have multiple
references pointing to it:
Person p1, p2;
p1 = new Person( );
p2 = p1;

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.2 Arrays of Objects


When an object has no references
pointing to it, the system will erase the
object and make the memory space
available again.
Erasing an object is called deallocation
of memory.
The process of deallocating memory is
called garbage collection. Garbage
collection is automatically performed in
Java.
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


Arrays and objects are reference data
types, so the rules for passing an object
to a method and returning an object from
a method apply to arrays.

Consider an example method that returns


the index of the smallest element in an
array of real numbers:

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


public int searchMinimum(double[] number) {
int indexOfMinimum = 0;
for (int i = 1; i < number.length; i++){
if (number[i] < number[indexOfMinimum]) {
//found a smaller element
indexOfMinimum = i;
}
}
return indexOfMinimum;
}

To call this method (from a method of the


same class), we write
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


double[] arrayOne;
//create and assign values to arrayOne
...
//get the index of the smallest element of
arrayOne
int minOne = searchMinimum(arrayOne);

//output the result


System.out.print(Minimum value in Array One
is );
System.out.print(arrayOne[minOne] + at
position + minOne);
...

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


Remember that when an array is
passed to a method, only its reference
is passed.
A copy of the array is not created in the
method.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.9A
Passing an array to a method means we
are passing a reference to an array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.9B
Passing an array to a method means we
are passing a reference to an array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.10A
Passing an array to a method means we
are passing a reference to an array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.10B
Passing an array to a method means we
are passing a reference to an array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


Next we will consider an example in
which we return an array from a
method.
This method inputs double values and
returns the values as an array of
double.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


public double[] readDoubles() {
double[] number;
int N = Integer.ParseInt(
JOptionPane.showInputDialog(null,
How many input values?));
number = new double[N];

for (int i = 0; i<N; i++){


number[i] = Double.parseDouble(
JOptionPane.showInputDialog(null,
Number + i));
}
return number;
}

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


The readDoubles method is called:
double[] arrayOne;
//assign values to arrayOne
arrayOne = readDoubles();

Because a new array is created by the


method, we do not have to create an
array from the calling side. Doing so
will not cause an error, but it is a
wasteful operation.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.3 Passing Arrays to Methods


Figures 10.11 and 10.12 examine the
effects of creating a local array and not
returning it.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.11A
The effect of creating a local array and not
returning it.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.11B
The effect of creating a local array and not
returning it.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.12A
The effect of creating a local array and not
returning it.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.12B
The effect of creating a local array and not
returning it.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


In Java, data may be organized in a
two-dimensional array.
A table is an example of a twodimensional array.
In a two-dimensional array, two indices
(in a table, one for the row and one for
the column) are used to refer to the
array element.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


To declare our example array, we state:
double[][] payScaleTable;

or
double payScaleTable[][];

and create the array as


payScaleTable = new double[4][5];

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.15
Examples of information represented as
tables.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


To refer to an element at the second
column (column 1) of the third row
(row 2), we say
payScaleTable[2][1]

Nested-for loops are useful for


manipulating two-dimensional arrays.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.16
Accessing an element of a twodimensional array.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


The concept of the two-dimensional
array in Java is just that: a concept.
There is no explicit structure called the
two-dimensional array in Java.

The two-dimensional array concept is


implemented by using an array of
arrays.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


The sample array creation
payScaleTable = new double[4][5];

is a shorthand for
payScaleTable = new double [4][ ];
payScaleTable[0] = new double [5];
payScaleTable[1] = new double [5];
payScaleTable[2] = new double [5];

and so on.
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.17A
Executing the statements on the left in
sequence will create the array of
arrays shown on the right.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 10.17B

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


The expression
payScaleTable.length

refers to the length of the


payScaleTable array itself.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


The expression
payScaleTable[1].length

refers to the length of the array stored at


row 1 of payScaleTable.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


An array that is part of another array is
called a subarray.
An array of arrays may be initialized
when it is created.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.5 Two-Dimensional Arrays


Subarrays may be different lengths.
Executing
triangularArray = new double[4][ ];
for (int i = 0; i < 4; i++)
triangularArray[i] = new double [i + 1];

results in an array that looks like:

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The java.util library contains highpower classes for maintaining a
collection of objects.
These classes are collectively referred
to as the Java Collection Framework
(JCF).

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The List interface is one useful feature
that can help us manage large
numbers of objects.
An interface defines the behavior of a
class; a list of public methods without
method bodies.

We cannot create an instance of an


interface.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


Two classes in the JCF implement the
List interface:
ArrayList
LinkedList

The ArrayList class uses an array to


manage data.
The LinkedList class uses a technique
called linked-node representation.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


To use the List interface, we declare
the variable as List and assign an
instance of the class that implements
the List interface to it:
List myList;
...
myList = new ArrayList( );

This approach permits a quick change


of the implementation class if
necessary.
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The default constructor will create an
empty list with an initial capacity of 10.
It is possible to increase the capacity of
a list. However, it is better to create a
list with the actual capacity we need, if
we know in advance what that
capacity is.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The add method allows us to add
objects to the list.
The capacity method gives us the
current capacity of a list.
To find out the number of objects
contained in a list, we use its size
method.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The remove method takes an elements
index as its parameter and allows us
to remove an element from a list.
The get method allows us to access
objects stored in a list by giving their
index position in the list.
The iterator method also allows us to
scan the elements inside a list or other
JCF collection classes.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


When we call a lists iterator method,
an Iterator object (an instance of a
class that implements the Iterator
interface) that supports two methods,
hasNext and next, is returned.

hasNext returns true if the iterator has


more elements to access.
Calling next if there are no more
elements to access will result in an
error.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The iterator method is supported by
many other java.util classes.
A list cannot include primitive data
values as its elements, but wrapper
classes can adapt the values to
acceptable list objects.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


Two classes implement the Map
interface:
HashMap
TreeMap

TreeMap implements a subinterface of


Map called SortedMap, where the
entries in the map are sorted.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


A map consists of entries. Each entry is
divided into two parts:
key
value

Duplicate keys are not allowed in the


map.
Both the key and the value may be
instances of any class.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


A map may be characterized as an
expandable array with instances of
any class as its indices.
The main advantage of a map is its
performance in locating an entry, given
the key.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


We create an instance of a map:
Map table;
...
table = new TreeMap();

We add the key-value pairs to the map:


table.put(CS0101, Great course. Take
it.);

The first argument is the key.


The second argument is the value.
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


To remove an entry from a map, we use
its remove method and pass the key
as the argument.
To retrieve all entries in the map, we
use the entrySet method.
To access all entries in a map, we use
the entrySet method to obtain a set of
entries, then use the iterator method
as in the ArrayList example.
TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

10.6 Lists and Maps


The getKey and getValue methods are
two particularly useful methods in the
interface.
These method retrieve the map entrys
key and value, respectively.

TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

You might also like