Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^500) | One-Dimensional Arrays


Arrays of User-Defined Objects


In the last example, the components of the array were strings. Now let’s look at an array of
user-defined objects. We have used a Nameclass in several Case Studies. The following code
declares and instantiates an array of elements of the class Name:

Name[] friends = new Name[10];

The following table shows the types involved and indicates how to access the various
components:

Expression Class/Type
friends Reference to an array
friends[0] Reference to a Nameobject
friends[0].knowFirst() Reference to a string
friends[0].knowLast() Reference to a string
friends[0].knowMiddle() Reference to a string
friends[0].knowFirst().charAt(1) A character

10.6 Arrays and Methods


The only observer method provided for arrays is component access, which has its own spe-
cial syntax: the array variable’s name, followed by an index enclosed in brackets. The index
specifies which component to access.
When we use an array as a field in a class, however, we may need to pass an array vari-
able as an argument to a method or pass a component of an array to a method. Recall that
a copy of each argument is sent to the method. Because an array, like a class, is a reference
type, the method receives the address indicating where the object is stored.
Suppose we define a publicclass method (say, in the class Accounting) that takes the ar-
ray as an argument and returns the sum of the components in the array:

public static doublesumSales(double[] data)
{
doublesum = 0.0;
for (int index = 0; index < data.length; index++)
sum = sum + data[index];
returnsum;
}

The following code uses the methodsumSalesto sum the week’s gourmet hamburger sales:

outFile.print("This week's sales of gourmet hamburgers: ");
outFile.println(Accounting.sumSales(gourmetBurgers));

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf