ARRAYS IN CLASSES AND METHODS

Một phần của tài liệu java an introductioan to problem solving and programming 6th edition (Trang 531 - 551)

A little more than kin, and less than kind.

—WILLIAM SHAKESPEARE,HAMLET

Arrays can be used as instance variables in classes. Methods can have an JOEFYFEWBSJBCMFPSBOFOUJSFBSSBZBTBOBSHVNFOUBOEDBOSFUVSOBOBSSBZ*O TIPSUBSSBZTDBOCFVTFEXJUIDMBTTFTBOENFUIPETKVTUBTPUIFSPCKFDUTDBO We begin with a case study that uses an array as an instance variable in a class.

CASE STUDY Sales Report

*O UIJT DBTF TUVEZ XF XJMM XSJUF B QSPHSBN UP HFOFSBUF TBMFT SFQPSUT GPS B company’s team of sales associates. The company wants to easily see which associate or associates have the highest sales and to know how the sales of each associate compare to the average.

4JODFXFOFFEUPSFDPSEBOBNFBOEUIFTBMFTGJHVSFTGPSFBDIBTTPDJBUFXF can design a class for a single sales associate that holds these two data items.

Our class can perform input and output and have a reasonable complement of accessor and mutator methods. This class definition is rather routine and is TIPXOJO-JTUJOH

The task’s specification

496 CHAPTER 7 / Arrays

LISTING 7.3 Sales Associate Class import java.util.Scanner;

/**

Class for sales associate records.

*/

public class SalesAssociate {

private String name;

private double sales;

public SalesAssociate() {

name = "No record";

sales = 0;

}

public SalesAssociate(String initialName, double initialSales) {

set(initialName, initialSales);

}

public void set(String newName, double newSales) {

name = newName;

sales = newSales;

}

public void readInput() {

System.out.print("Enter name of sales associate: ");

Scanner keyboard = new Scanner(System.in);

name = keyboard.nextLine();

System.out.print("Enter associate's sales: $");

sales = keyboard.nextDouble();

}

public void writeOutput() {

System.out.println("Name: " + name);

System.out.println("Sales: $" + sales);

}

public String getName() {

return name;

}

public double getSales() {

return sales;

} }

Our program will need an array to keep track of the data for all sales associates. It will also need to record the highest sales and the average sales.

5IFSFGPSFXFXJMMOFFEUPEFTJHOBOPUIFSDMBTT8FDBOHJWFPVSOFXDMBTTUIF following instance variables to record the desired data:

private double highestSales;

private double averageSales;

private SalesAssociate[] team;

We need to know the number of associates. This number will be the same as team.length CVU IBWJOH B TFQBSBUF XFMMOBNFE WBSJBCMF GPS UIF OVNCFS PG BTTPDJBUFT JT B HPPE JEFB 4P MFUT JODMVEF UIF GPMMPXJOH instance variable:

private int numberOfAssociates; //Same as team.length The job of our program breaks down into these main subtasks:

1. Get ready.

2. Obtain the data.

$PNQVUFTPNFTUBUJTUJDT VQEBUFUIFJOTUBODFWBSJBCMFT %JTQMBZUIFSFTVMUT

8FTIPVMEOBNFPVSOFXDMBTTBOEJUTNFUIPET5PPSHBOJ[FPVSUIPVHIUTXF DBOESBXUIFDMBTTEJBHSBNTIPXOJO'JHVSF 5IVTXFLOPXUIBUPVSDMBTT will look like this:

public class SalesReporter {

private double highestSales;

private double averageSales;

private SalesAssociate[] team;

private int numberOfAssociates; //Same as team.length public static void main(String[ ] args)

{

SalesReporter clerk = new SalesReporter();

clerk.getData();

clerk.computeStats();

clerk.displayResults();

}

<More stuff needs to be added here.>

}

"MMUIBUSFNBJOTJTUPXSJUFUIFUISFFNFUIPETgetData, computeStats, and displayResults and to test and debug the program. We will tackle the three methods in order.

The instance variables

The program’s subtasks

498 CHAPTER 7 / Arrays

FIGURE 7.3 Class Diagram for the Class Sales Reporter

SalesReporter - highestSales: double

- averageSales: double - team: SalesAssociate[]

- numberOfAssociates: int

+ getData(): void + computeStats(): void + displayResults(): void

The input method getData JT SFMBUJWFMZ TUSBJHIUGPSXBSE FTQFDJBMMZ since we have an input method for objects of the class SalesAssociate.

"GUFS XF SFBE UIF OVNCFS PG BTTPDJBUFT XF DBO XSJUF UIF GPMMPXJOH CBTJD input loop:

for (int i = 1; i <= numberOfAssociates; i++) {

System.out.println("Enter data for associate number" + i);

team[i].readInput();

}

"MUIPVHI UIF BSSBZ JOEJDFT CFHJO BU BOE UIF BTTPDJBUFT BSF OVNCFSFE TUBSUJOHXJUIXFIBWFVTFEteam[i] for associate i5IBUJTXFEFDJEFEUP ignore team[0]5IVTXFOFFEUPBMMPDBUFBOFYUSBMPDBUJPOJOUIFBSSBZBT follows:

team = new SalesAssociate[numberOfAssociates + 1];

4JODFXFSFBEnumberOfAssociates in getDataXFXJMMQMBDFUIJTTUBUFNFOU in that method as well.

#VUBOPUIFSQSPCMFNSFNBJOT8IFOXFUFTUUIFQSFWJPVTMPPQXFXJMMHFU BOFSSPSNFTTBHFTBZJOHTPNFUIJOHBCPVUBiOVMMQPJOUFSw5IJTQSPCMFNBSJTFT because the base type of the array team JT B DMBTT UZQF 5P TFF UIF QSPCMFN DPOTJEFSBOPUIFSTJUVBUJPOGJSTU4VQQPTFXFIBEUIFGPMMPXJOHDPEF

SalesAssociate s;

s.readInput();

5IJTDPEFXPVMEQSPEVDFUIFTBNFFSSPSNFTTBHFSFHBSEJOHBiOVMMQPJOUFSw The problem is that the variable s is just a name; it does not yet reference any The loop in

getData

Associatei is in team[i]

object of the class SalesAssociate. The preceding code omitted the usual use ofnew. The code should be

SalesAssociate s = new SalesAssociate();

s.readInput();

5IFJOEFYFEWBSJBCMFteam[i]JTBMTPBWBSJBCMFPGBDMBTTUZQFBOETPJU is also just a name. You need to assign a SalesAssociate object to team[i]

CFGPSFFYFDVUJOH

team[i].readInput();

5IVTXFOFFEUPBEEUIFGPMMPXJOHTUBUFNFOUUPPVSMPPQ team[i] = new SalesAssociate();

The complete definition of the method getData with this line inserted is TIPXOJO-JTUJOH

LISTING 7.4 A Sales Report Program (part 1 of 3) import java.util.Scanner;

/**

Program to generate sales report.

*/

public class SalesReporter {

private double highestSales;

private double averageSales;

private SalesAssociate[] team; //The array object is //created in getData.

private int numberOfAssociates; //Same as team.length /**

Reads the number of sales associates and data for each one.

*/

public void getData() {

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter number of sales associates:");

numberOfAssociates = keyboard.nextInt();

team = new SalesAssociate[numberOfAssociates + 1];

for (int i = 1; i <= numberOfAssociates; i++) {

team[i] = new SalesAssociate();

System.out.println("Enter data for associate " + i);

team[i].readInput();

System.out.println();

} }

Themain method is at the end of the class.

Array object created here.

SalesAssociate objects created here.

(continued)

500 CHAPTER 7 / Arrays

LISTING 7.4 A Sales Report Program (part 2 of 3) /**

Computes the average and highest sales figures.

Precondition: There is at least one salesAssociate.

*/

public void computeStats() {

double nextSales = team[1].getSales();

highestSales = nextSales;

double sum = nextSales;

for (int i = 2; i <= numberOfAssociates; i++) {

nextSales = team[i].getSales();

sum = sum + nextSales;

if (nextSales > highestSales)

highestSales = nextSales; //highest sales so far.

}

averageSales = sum / numberOfAssociates;

} /**

Displays sales report on the screen.

*/

public void displayResults() {

System.out.println("Average sales per associate is $" + averageSales);

System.out.println("The highest sales figure is $" + highestSales);

System.out.println();

System.out.println("The following had the highest sales:");

for (int i = 1; i <= numberOfAssociates; i++) {

double nextSales = team[i].getSales();

if (nextSales == highestSales) {

team[i].writeOutput();

System.out.println("$" + (nextSales - averageSales) + " above the average.");

System.out.println();

} }

System.out.println("The rest performed as follows:");

for (int i = 1; i <= numberOfAssociates; i++) {

double nextSales = team[i].getSales();

if (team[i].getSales() != highestSales) {

(continued) Already processed team[1], so the loop starts with team[2].

LISTING 7.4 A Sales Report Program (part 3 of 3) team[i].writeOutput();

if (nextSales >= averageSales)

System.out.println("$" + (nextSales -

averageSales) + " above the average.");

else

System.out.println("$" + (averageSales - nextSales) + " below the average.");

System.out.println();

} } }

public static void main(String[] args) {

SalesReporter clerk = new SalesReporter();

clerk.getData();

clerk.computeStats();

clerk.displayResults();

} }

Sample Screen Output

Enter number of sales associates:

3

Enter data for associate number 1

Enter name of sales associate: Dusty Rhodes Enter associate's sales: $36000

Enter data for associate number 2

Enter name of sales associate: Natalie Dressed Enter associate's sales: $50000

Enter data for associate number 3

Enter name of sales associate: Sandy Hair Enter associate's sales: $10000

Average sales per associate is $32000.0 The highest sales figure is $50000.0 The following had the highest sales:

Name: Natalie Dressed Sales: $50000.0

$18000.0 above the average.

The rest performed as follows:

Name: Dusty Rhodes Sales: $36000.0

$4000.0 above the average.

Name: Sandy Hair Sales: $10000.0

$22000.0 below the average.

502 CHAPTER 7 / Arrays

/FYU XF UVSO PVS BUUFOUJPO UP UIF NFUIPEcomputeStats and come up with the following code:

for (int i = 1; i <= numberOfAssociates; i++) {

sum = sum + team[i].getSales();

if (team[i].getSales() > highest)

highestSales = team[i].getSales();//highest sales

} //so far.

average = sum / numberOfAssociates;

5IJTMPPQJTCBTJDBMMZ0,CVUUIFWBSJBCMFTsum and highest must be initialized CFGPSFUIFMPPQCFHJOT8FDBOJOJUJBMJ[FTVNUPCVUXIBUWBMVFEPXFVTFUP initializehighest 1FSIBQTBOFHBUJWFOVNCFSTJODFTBMFTDBOOPUCFOFHBUJWF 0SDBOUIFZ *GBDVTUPNFSSFUVSOTHPPETUIBUJTDPOTJEFSFEBOFHBUJWFTBMFTP TBMFTDBOJOEFFECFOFHBUJWF)PXFWFSXFLOPXUIBUUIFDPNQBOZBMXBZTIBT BUMFBTUPOFTBMFTBTTPDJBUFBOETPXFDBOJOJUJBMJ[FCPUIsum and highest to the sales for the first associate. This takes one case outside the loop and places JUCFGPSFUIFMPPQBTGPMMPXT

highestSales = team[1].getSales();

double sum = team[1].getSales();

for (int i = 2; i <= numberOfAssociates; i++) {

sum = sum + team[1].getSales();

if (team[i].getSales() > highest)

highestSales = team[i].getSales();//highest sales //so far.

}

average = sum / numberOfAssociates;

5IFQSFDFEJOHMPPQXJMMXPSLCVUOPUJDFUIFSFQFBUFEDBMDVMBUJPO8FIBWF three identical method invocations of team[i].getSales(). To avoid this EVQMJDBUJPOXFDBOTUPSFUIFSFTVMUPGPOFTVDIJOWPDBUJPOJOBWBSJBCMFBTGPMMPXT

double nextSales = team[1].getSales();

highestSales = nextSales;

double sum = nextSales;

for (int i = 2; i <= numberOfAssociates; i++) {

nextSales = team[i].getSales();

sum = sum + nextSales;

if (nextSales> highest)

highest = nextSales; //highest sales so far.

}

average = sum / numberOfAssociates;

The complete definition of the method computeStatsJTHJWFOJO-JTUJOH 5IFEFTJHOPGUIFMBTUNFUIPEdisplayResultsVTFTPOMZUFDIOJRVFTUIBU ZPVIBWFBMSFBEZTFFOBOETPXFXJMMOPUHPPWFSUIFEFUBJMT*UTEFGJOJUJPOJT

TIPXOJO-JTUJOH ■

A draft of the loop in computeStats

A revised loop in computeStats

The final loop in computeStats

VideoNote

Using arrays within a class

Indexed Variables as Method Arguments

"OJOEFYFEWBSJBCMFGPSBOBSSBZaTVDIBTa[i]DBOCFVTFEBOZXIFSFUIBU ZPV DBO VTF BOZ PUIFS WBSJBCMF PG UIF CBTF UZQF PG UIF BSSBZ 4P BO JOEFYFE WBSJBCMF DBO CF BO BSHVNFOU UP B NFUIPE JO FYBDUMZ UIF TBNF XBZ UIBU BOZ other variable of the array’s base type can be an argument.

'PSFYBNQMFUIFQSPHSBNJO-JTUJOHJMMVTUSBUFTUIFVTFPGBOJOEFYFE variable as an argument to a method. The method getAverage takes two arguments of type int. The array nextScore has the base type intBOETPUIF program can use nextScore[i] as an argument to the method getAverageBT in the following line from that program:

double possibleAverage = getAverage(firstScore,nextScore[i]);

The variable firstScore is an ordinary variable of type int. To help drive IPNFUIFQPJOUUIBUUIFJOEFYFEWBSJBCMFnextScore[i] can be used just like any other variable of type intOPUFUIBUgetAverageXPVMECFIBWFJOFYBDUMZ UIFTBNFXBZJGXFJOUFSDIBOHFEJUTUXPBSHVNFOUTBTGPMMPXT

double possibleAverage = getAverage(nextScore[i],firstScore);

The definition of the method getAverage contains no indication that its BSHVNFOUT DBO CF JOEFYFE WBSJBCMFT GPS BO BSSBZ PGint. The method accepts arguments of type int BOE OFJUIFS QBSBNFUFS LOPXT OPS DBSFT XIFUIFS UIPTF intsDBNFGSPNBOJOEFYFEWBSJBCMFBSFHVMBSintWBSJBCMFPSBDPOTUBOUWBMVF

5IFSF JT POF TVCUMFUZ UIBU BQQMJFT UP JOEFYFE WBSJBCMFT XIFO VTFE BT NFUIPEBSHVNFOUT'PSFYBNQMFDPOTJEFSFJUIFSPGUIFQSFWJPVTNFUIPEDBMMT If the value of iJTUIFBSHVNFOUJTnextScore[2]0OUIFPUIFSIBOEJGUIF value of iJTUIFBSHVNFOUJTnextScore[0]5IFFYQSFTTJPOVTFEBTBOJOEFY JTFWBMVBUFEUPEFUFSNJOFFYBDUMZXIJDIJOEFYFEWBSJBCMFJTUIFBSHVNFOU

#FTVSFUPOPUFUIBUBOJOEFYFEWBSJBCMFPGBOBSSBZaTVDIBTa[i]JTB variable of the base type of the array. When a[i] is used as an argument to a NFUIPEJUJTIBOEMFEJOFYBDUMZUIFTBNFXBZBTBOZPUIFSWBSJBCMFPGUIFCBTF type of the array a*OQBSUJDVMBSJGUIFCBTFUZQFPGUIFBSSBZJTBQSJNJUJWFUZQF

S E L F - T E S T Q U E S T I O N S

8SJUF TPNF +BWB DPEF UIBU XJMM EFDMBSF BO BSSBZ OBNFEentry that has MFOHUIIBTSalesAssociate -JTUJOHBTJUTCBTFUZQFBOEJTGJMMFE with three identical records. The records use the name "Jane Doe" and TBMFTPG6TFBfor loop.

8. Rewrite the method displayResults of the program SalesReporter -JTUJOHTPUIBUJUVTFTUIFNFUIPETJOUIFDMBTTDollarFormat -JTUJOH PG$IBQUFSUPEJTQMBZUIFEPMMBSBNPVOUTJOUIFDPSSFDUGPSNBUGPS dollars and cents.

An indexed variable can be an argument

The value of the index affects the value of the argument

504 CHAPTER 7 / Arrays

LISTING 7.5 Indexed Variables as Arguments

import java.util.Scanner;

/**

A demonstration of using indexed variables as arguments.

*/

public class ArgumentDemo {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter your score on exam 1:");

int firstScore = keyboard.nextInt();

int[] nextScore = new int[3];

for (int i = 0; i < nextScore.length; i++) nextScore[i] = firstScore + 5 * i;

for (int i = 0; i < nextScore.length; i++) {

double possibleAverage =

getAverage(firstScore, nextScore[i]);

System.out.println("If your score on exam 2 is " + nextScore[i]);

System.out.println("your average will be " + possibleAverage);

} }

public static double getAverage(int n1, int n2) {

return (n1 + n2) / 2.0;

} }

Sample Screen Output Enter your score on exam 1:

80

If your score on exam 2 is 80 your average will be 80.0 If your score on exam 2 is 85 your average will be 82.5 If your score on exam 2 is 90 your average will be 85.0

such as intdouble PSchar UIF NFUIPE DBOOPU DIBOHF UIF WBMVF PGa[i]. 0O UIF PUIFS IBOE JG UIF CBTF UZQF PG UIF BSSBZ JT B DMBTT UZQF UIF NFUIPE can change the state of the object named by a[i]. This is nothing new. Just SFNFNCFSUIBUBOJOEFYFEWBSJBCMFTVDIBTa[i]JTBWBSJBCMFPGUIFCBTFUZQF of the array and is handled just like any other variable of that data type.

RECAP Indexed Variables as Arguments

An indexed variable can be used as an argument anywhere that a variable of the array’s base type can be used. For example, suppose you have

double[] a = new double[10];

Indexed variables such as a[3] and a[index] can then be used as arguments to any method that accepts a value as an argument.

FAQ When can a method change an argument that is an indexed variable?

Supposea[i] is an indexed variable of the array a and a[i] is used as an argument in a method invocation such as

doStuff(a[i]);

Whether the method doStuff can change the array element a[i]

depends on the base type of the array a. If the base type of the array a is a primitive type, such as int,double or char, the method doStuff receives the value of a[i], and so cannot change a[i] itself, However, if the base type of the array a is a class, the method dostuff receives a reference to a[i]. Thus, the method can change the state of the object named by a[i], but cannot replace the object with another one. (To review the details on method arguments, see Chapter 5.)

Entire Arrays as Arguments to a Method

:PVIBWFBMSFBEZTFFOUIBUBOJOEFYFEWBSJBCMFPGBOBSSBZDBOCFVTFEBTBO argument to a method. An entire array can also be used as an argument to a method. The way you specify an array parameter in a method definition is TJNJMBSUPUIFXBZZPVEFDMBSFBOBSSBZ'PSFYBNQMFUIFGPMMPXJOHNFUIPE

506 CHAPTER 7 / Arrays

incrementArrayBy2 will accept as its one argument any array whose base type isdouble:

public class SampleClass {

public static void incrementArrayBy2(double[] anArray) {

for (int i = 0; i <anArray.length; i++) anArray[i] = anArray[i] + 2;

}

<The rest of the class definition goes here.>

}

8IFO ZPV TQFDJGZ BO BSSBZ QBSBNFUFS ZPV HJWF UIFCBTFUZQFPGUIFBSSBZCVUZPVEPOPUGJYUIF length of the array.

5P JMMVTUSBUF UIF VTF PG UIJT TBNQMF DMBTT suppose you have the statements

double[] a = new double[10];

double[] b = new double[30];

XJUIJOTPNFNFUIPEEFGJOJUJPOBOETVQQPTFUIBU the elements of the arrays a and b have been given WBMVFT#PUIPGUIFGPMMPXJOHNFUIPEJOWPDBUJPOT are then valid:

SampleClass.incrementArrayBy2(a);

SampleClass.incrementArrayBy2(b);

The method incrementArrayBy2 can take an array of any length as its BSHVNFOUBOEDBODIBOHFUIFWBMVFTPGUIFFMFNFOUTJOUIFBSSBZ'PMMPXJOH UIF QSFWJPVT JOWPDBUJPOT PG UIF NFUIPE UIF FMFNFOUT JO UIF BSSBZTa and b have each been increased by 2.

A parameter can represent an entire array

ASIDE Alternative Syntax for Array Parameters

There is an alternative syntax for array parameters, similar to the alternative syntax for declaring an array. You can write the square brackets after the parameter instead of after the base type, as in the following example:

public static void showArray (char a[])

We do not encourage the use of this alternative syntax, however.

A method can change the values of the elements in its array argument

RECAP Array Parameters

An argument to a method may be an entire array. You use the following syntax for the method’s heading:

SYNTAX

public static Return_Type Method_Name(Base_Type[] Param_Name) You can use other modifiers instead of public and static.

(continued)

REMEMBER Array Parameters Do Not Specify the Array Length An array parameter in a method’s heading specifies the base type of the array, but not the length of the array. For example, the following method heading specifies an array of characters as a parameter:

public static void showArray(char[] a)

REMEMBER Characteristics of Array Arguments

t /PTRVBSFCSBDLFUTBSFXSJUUFOXIFOZPVQBTTBOFOUJSFBSSBZBTBOBSHVNFOU UPBNFUIPE

t "OBSSBZPGBOZMFOHUIDBOCFUIFBSHVNFOUDPSSFTQPOEJOHUPBOBSSBZ QBSBNFUFS

t "NFUIPEDBODIBOHFUIFWBMVFTJOBOBSSBZBSHVNFOU

Each of these points is demonstrated by the preceding method incrementArrayBy2.

EXAMPLES

public static int getOneElement(char[] anArray, int index) public void readArray(int[] anotherArray)

Arguments for the Method main

The heading for the main method of a program is as follows:

public static void main(String[] args)

The parameter declaration String[] args indicates that args is an array whose base type is String5IBUJTUIFNFUIPEmain takes an array of String WBMVFTBTBOBSHVNFOU#VUXFOFWFSIBWFHJWFOmain an argument when we SBO BOZ PG PVS QSPHSBNT *O GBDU XF IBWF OFWFS JOWPLFEmain! What’s the TUPSZ

"TZPVLOPXBOJOWPDBUJPOPGmain is a very special sort of invocation that XFEPOPUNBLF8IFOZPVSVOZPVSQSPHSBNmain is invoked automatically BOEHJWFOBEFGBVMUBSSBZPGTUSJOHTBTBEFGBVMUBSHVNFOU#VUZPVDBOJGZPV MJLF QSPWJEF BEEJUJPOBM TUSJOHT XIFO ZPV SVO B QSPHSBN BOE UIPTF TUSJOHT will automatically be made elements of the array args that is provided to

508 CHAPTER 7 / Arrays

mainBTBOBSHVNFOU/PSNBMMZZPVEPUIJTCZSVOOJOHUIFQSPHSBNGSPNUIF DPNNBOEMJOFPGUIFPQFSBUJOHTZTUFNMJLFTP

java TestProgram Sally Smith

This command sets args[0] to "Sally" and args[1] to "Smith". These two JOEFYFEWBSJBCMFTDBOUIFOCFVTFEXJUIJOUIFNFUIPEmain.

'PSFYBNQMFDPOTJEFSUIFGPMMPXJOHTBNQMFQSPHSBN public class TestProgram

{

public static void main(String[] args) {

System.out.println("Hello" + args[0] + " " + args[1]);

} }

After running TestProgram using the one-line command java TestProgram Josephine Student

the output produced by the program will be Hello Josephine Student

#FTVSFUPOPUFUIBUUIFBSHVNFOUUPmain is an array of strings. If you want OVNCFSTZPVNVTUDPOWFSUUIFTUSJOHSFQSFTFOUBUJPOTPGUIFOVNCFSTUPWBMVFT PGPOFPSNPSFOVNCFSUZQFT'PSFYBNQMFUPDPOWFSUUIFGJSTUBSHVNFOUUPBO JOUFHFSZPVDPVMEVTFInteger.parseInt(args[0])4JODFUIFJEFOUJGJFSargs JTBQBSBNFUFSZPVDBOVTFBOZPUIFSWBMJEJEFOUJGJFSJOQMBDFPGargsBTMPOH as you change any occurrences of args that also occur in the body of main. )PXFWFSJUJTUSBEJUJPOBMUPVTFUIFJEFOUJGJFSargs for this parameter.

Array Assignment and Equality

"SSBZTBSFPCKFDUTBOETPUIFBTTJHONFOUPQFSBUPSBOEUIFFRVBMJUZPQFSBUPS CFIBWF BOENJTCFIBWFJOUIFTBNFXBZXJUIBSSBZTBTUIFZEPXJUIUIF kinds of objects we saw before discussing arrays. To understand how this BQQMJFTUPBSSBZTZPVOFFEUPLOPXBMJUUMFCJUBCPVUIPXBSSBZTBSFTUPSFEJO the computer’s main memory. The important point for this discussion is that UIFFOUJSFBSSBZDPOUFOUT‰UIBUJTUIFDPOUFOUTPGBMMPGUIFJOEFYFEWBSJBCMFT‰

BSFTUPSFEUPHFUIFSJOPOFQPTTJCMZMBSHFTFDUJPOPGNFNPSZ*OUIJTXBZUIF location of the entire array contents can be specified by one memory address.

Recall that a variable for an object really contains the memory address of UIFPCKFDU5IFBTTJHONFOUPQFSBUPSDPQJFTUIJTNFNPSZBEESFTT'PSFYBNQMF consider the following code:

int[] a = new int[3];

int[] b = new int[3];

for (int i = 0; i <a.length; i++) a[i] = i;

You can pass an array of strings tomain as an argument

b = a;

System.out.println("a[2] = " + a[2] + ", b[2] = " + b[2]);

a[2] = 2001;

System.out.println("a[2] = " + a[2] + ", b[2] = " + b[2]);

This will produce the following output:

a[2] = 2, b[2] = 2 a[2] = 2001, b[2] = 2001

The assignment b = a in the preceding code gives the array variable b the same memory address as the array variable a4Pa and b are two different names for UIFTBNFBSSBZ5IVTXIFOXFDIBOHFUIFWBMVFPGa[2]XFBSFBMTPDIBOHJOHUIF value of b[2]'PSUIJTSFBTPOJUJTCFTUTJNQMZOPUUPVTFUIFBTTJHONFOUPQFSBUPS XJUIBSSBZT*GZPVXBOUUIFBSSBZTa and b in the preceding code to be different BSSBZTIBWJOHUIFTBNFWBMVFTZPVNVTUXSJUFTPNFUIJOHMJLFUIFGPMMPXJOH

for (int i = 0; i < a.length; i++) b[i] = a[i];

instead of the assignment statement b = a;

Note that the preceding loop assumes that the arrays a and b have the same length.

5IFFRVBMJUZPQFSBUPSUFTUTXIFUIFSUXPBSSBZTBSFTUPSFEJOUIFTBNF QMBDFJOUIFDPNQVUFSTNFNPSZ'PSFYBNQMFUIFDPEF

int[] a = new int[3];

int[] b = new int[3];

for (int i = 0; i < a.length; i++) a[i] = i;

for (int i = 0; i < b.length; i++) b[i] = i;

if (b == a)

System.out.println("Equal by ==");

else

System.out.println("Not equal by ==");

produces the output Not equal by ==

&WFOUIPVHIUIFBSSBZTBOEDPOUBJOUIFTBNFJOUFHFSTJOUIFTBNFPSEFSUIF BSSBZTBSFTUPSFEJOEJGGFSFOUQMBDFTJONFNPSZ4PbaJTGBMTFTJODFUFTUT GPSFRVBMNFNPSZBEESFTTFT

*G ZPV XBOU UP UFTU XIFUIFS UXP BSSBZT DPOUBJO UIF TBNF FMFNFOUT ZPV NVTUUFTUXIFUIFSFBDIFMFNFOUJOPOFBSSBZFRVBMTUIFDPSSFTQPOEJOHFMFNFOU JOUIFPUIFSBSSBZ-JTUJOHDPOUBJOTBTNBMMEFNPOTUSBUJPODMBTTUIBUTIPXT one possible way to do this.

Assigning one array to another results in one array having two names

The operator ==

tests whether two arrays are at the same place in memory

510 CHAPTER 7 / Arrays

LISTING 7.6 Two Kinds of Equality(part 1 of 2) /**

A demonstration program to test two arrays for equality.

*/

public class TestEquals {

public static void main(String[] args) {

int[] a = new int[3];

int[] b = new int[3];

setArray(a);

setArray(b);

if (b == a)

System.out.println("Equal by ==.");

else

System.out.println("Not equal by ==.");

if (equals(b, a))

System.out.println("Equal by the equals method.");

else

System.out.println("Not equal by the equals method.");

}

public static boolean equals(int[] a, int[] b) {

boolean elementsMatch = true;//tentatively if (a.length != b.length)

elementsMatch = false;

else {

int i = 0;

while (elementsMatch && (i < a.length)) {

if (a[i] != b[i])

elementsMatch = false;

i++;

} }

return elementsMatch;

}

public static void setArray(int[] array) {

for (int i = 0; i < array.length; i++) array[i] = i;

} }

(continued) The arrays a and b

contain the same integers in the same order.

LISTING 7.6 Two Kinds of Equality(part 2 of 2)

Screen Output Not equal by ==.

Equal by the equals method.

GOTCHA Using the Operators = and == with Arrays

:PVDBOVTFUIFBTTJHONFOUPQFSBUPSUPHJWFBOBSSBZNPSFUIBOPOFOBNF:PV DBOOPUVTFJUUPDPQZUIFDPOUFOUTPGPOFBSSBZUPBOPUIFSEJGGFSFOUBSSBZ-JLFXJTF UIFFRVBMJUZPQFSBUPSUFTUTXIFUIFSUXPBSSBZOBNFTSFGFSFODFUIFTBNFNFNPSZ address. It does not test whether two different arrays contain the same values. ■

REMEMBER Array Types Are Reference Types

A variable of an array type holds only the address where the array is stored in memory. This memory address is called a reference to the array object in memory. For this reason, array types are often called reference types. Recall from Chapter 5 that a reference type is any type whose variables hold references—that is, memory addresses—as opposed to the actual item named by the variable. Array types and class types are both reference types. Primitive types are not reference types.

FAQ Are arrays really objects?

Arrays do not belong to any class. Some other features of class objects—

such as inheritance, which we will discuss in Chapter 8—do not apply to arrays. So whether arrays should be considered objects is not 100 percent clear. However, that is primarily an academic debate. In Java, arrays are officially objects. Whenever Java documentation says that something applies to all objects, it also applies to arrays.

Methods That Return Arrays

"+BWBNFUIPENBZSFUVSOBOBSSBZ5PIBWFJUEPTPZPVTQFDJGZUIFNFUIPET SFUVSOUZQFJOUIFTBNFXBZUIBUZPVTQFDJGZUIFUZQFPGBOBSSBZQBSBNFUFS'PS FYBNQMF -JTUJOH DPOUBJOT B SFWJTFE WFSTJPO PG UIF QSPHSBN JO -JTUJOH

#PUI QSPHSBNT QFSGPSN QSFUUZ NVDI UIF TBNF DPNQVUBUJPOT CVU UIJT OFX version computes the various possible average scores within a method named

Một phần của tài liệu java an introductioan to problem solving and programming 6th edition (Trang 531 - 551)

Tải bản đầy đủ (PDF)

(987 trang)