面向对象程序设计 java 讲义 Arrays-Notes_第1页
面向对象程序设计 java 讲义 Arrays-Notes_第2页
面向对象程序设计 java 讲义 Arrays-Notes_第3页
面向对象程序设计 java 讲义 Arrays-Notes_第4页
面向对象程序设计 java 讲义 Arrays-Notes_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

COMP110/401PrasunDewanCopyrightPrasunDewan,2000.CopyrightPrasunDewan,2000.14.ArraysAstringisonekindofsequence.Inthischapter,wewillseehowwecancreatearbitrarysequencesusingarrays.Wewillusearraystocreateseveralnewkindsoftypesincludingsets,histories,anddatabases.Someofthesetypescanbeconsideredasspecialcasesofothertypes.Togetexperiencewithprocessingarrays,wewillstudyanotherkindofloopstatement,calledtheforloop.Theforloophasadifferentsyntaxthanthewhileloop,butwewillseethatinfacttheyareequivalent–whateveryoucandowithaforloop,youcandowithawhileloop,andviceversa.ForLoopThefollowingprogramfragmentillustratesstringmanipulation,printingthecharactersofastringonseparatelines://Stringsdeclaredandinitializedearlierinti=0;//initializationofloopvariableswhile(i<s.length()){//continuationconditionSystem.out.println(s.charAt(i));//realbodyi++;//resettingloopvariables}Thisisanexampleofacounter-controlledloop,sincethevariableiservesasacounterthatisincrementedineachiterationoftheloop.Itisalsoanexampleofanindex-controlledloop,whichisaspecialcaseofacounter-controlledloopinwhichthecounterisanindex.Letuslookatthiscodeinmoredepthtograspthegeneralnatureofaloop.Wecandecomposeitintothefollowingcomponents:Continuationcondition:thebooleanexpressionthatdeterminesifthenextiterationoftheloopshouldbeexecuted.Initializationofloopvariables:thefirstassignmentofvariablesthatappearinthecontinuationconditionandarechangedintheloopbody.Resettingloopvariables:preparingforthenextiterationbyreassigningoneormoreloopvariables.Realbody:therestofthewhilebody,whichdoesthe"real-work"ofeachiteration.Thewhileloopseparatesthecontinuingconditionfromtherestofthecomponents,therebyensuringwedonotforgettoenterit.However,itdoesnotseparatetheremainingcomponents–wehaveaddedcommentstodosointheexampleabove.Asaresult,wemayforgettocreateoneormoreofthesecomponents.Forinstance,wemayforgettoresettheloopvariables,therebycreatinganinfiniteloop.Javaprovidesanotherloop,theforlooporforstatement,illustratedbelow,whichexplicitlyseparatesallfourcomponents:for(inti=1;i<s.length();i++)System.out.println(s.charAt(i));Thisloopisequivalenttotheprogramfragmentabove.Ingeneral,aforstatementisoftheform:for(S1;E;S2)S3Itisequivalentto:S1;while(E){S3;S2;}Inotherwords,theforloopfirstexecutesS1andthenessentiallyexecutesawhileloopwhoseconditionisEandwhosebodyisS3followedbyS2.S1andS2areexpectedtoinitializeandreset,respectively,theloopvariables.Incomparisontoawhileloop,aforloopismorecompact.Moreimportant,itsstructureremindsustoenterS1andS2,thatis,initializeandresettheloopvariables.Anyofthethreepartsofaforloop,S1,E,andS2can,infact,bemissing.AmissingS1orS2isconsideredanullstatement,whileamissingEisconsideredtrue.Thus:for(;;){S3;}isequivalentto: while(true){ S3;}Abreakstatementcanbeusedtoexitbothkindsofloops.Wewilllearnaboutbreakstatementslater.ArraysAstringisasequenceofvaluesoftypechar.Whatifwewantedasequenceofothertypesofvaluessuchasint,double,orStringvalues?Onecouldimaginerestrictedsolutionstothisproblem.JavacouldprovideanIntSequencetypefordefiningsequencesofintvalues.Similarly,itcoulddefinethetypesDoubleSequence,StringSequence,andsoon.Theproblemwiththisapproachisthatnomatterhowmanypredefinedsequencetypeswehave,wemightwantakindofsequencethatwasnotanticipatedbyJava.Forinstance,whatifwewantedasequenceofinstancesofthetypeLoanwedefinedearlier?ThisisnotatypeknowntoJava,soitcannotpredefinesuchasequence.Therefore,instead,itletsus,asprogrammers,defineourownindexablesequences,calledarrays,whichcancontainelementsofsometypespecifiedbyus.Likeothervalues,theycanbestoredinvariablesoftheappropriatetype.Thefollowingdeclarationillustrateshowanarrayvariableandarrayvaluearecreated:String[]names={"JohnSmith","JaneDoe"};Letusdecomposethisdeclarationtobetterunderstandit:Thevariabledefinition:String[]namesdeclaredanewarrayvariable,callednames,whosetypeisString[].String[]denotesthestring-arraytype,thatis,itisthetypeofanarraywithStringelements.Thusthedefinitionsaysthatthevariablenamescanstorestring-arrays.Theexpression:{"JohnSmith","JaneDoe"};createsanewstring-arrayconsistingofthetwostrings,“JohnSmith”and“JaneDoe”.Thisexpressioncanbeconsideredasanarrayliteral;likeotherliteralswehaveseenbefore,itdirectlyindicatesavalueratherthanidentifyingavariablestoringthevalue.Theinitializationassignment:names={"JohnSmith","JaneDoe"};assignsthestring-arrayvalueontheRHStothestring-arrayvariableontheLHS.String[]isthetypeofallstringarrays,regardlessoftheirsize.Astring-arrayvariable,thus,canbeassignedstringarraysofdifferentsizes.Forinstance,wecanreassigntonamesa3-elementarray:names={"JohnSmith","JoeDoe","JaneDoe"};Similarly,wecancreateandinitializeothertypesofarrays:int[]scores={45,32,68};Loan[]loans={newALoan(100000),newAnotherLoan(100)};LikeString,anarraytypeisavariablebutnotadynamictype,thatis,itsinstancescanhavedifferentsizesbutthesizeofaparticulararrayisfixedduringitslifetime.Thus,whenwereassignednamesabove,wedidnotextendthesizeofthearraytowhichitwasassigned;instead,weassigneditanewarraywithalargersize.Likeothervariables,arrayvariablesneednotbeinitializedwhentheyarecreated.Instead,wecanassigntothemlaterinaseparateassignmentstatement,asshownbelowJavaalsoacceptsanalternativesyntaxfordeclaringarrayvariables.Inadditiontothesyntax:Javaalsoacceptsanalternativesyntaxfordeclaringarrayvariables.Inadditiontothesyntax:<ElementType>[]<StringArrayVariable>itallows:<ElementType><StringArrayVariable>[]Thus,Stringnames[];isequivalentto:String[]names;String[]names;names={"JohnSmith","JaneDoe"};Infact,wehavealreadyseenthesyntaxfordeclaringuninitializedarrayvariableswhiledeclaringamainmethod:publicstaticvoidmain(String[]args)Theformalparameter,args,isdeclaredasanuninitializedstringarray.Whenauserentersalistofstringarguments,Javastoresthelistinastringarray,andassignsthisvaluetotheformalparameter.AccessingandModifyingArrayElementsLikestrings,arrayscanbeindexed,butthesyntaxfordoingsoismoreconvenient.Eventhougharraysareobjects,wedonotinvokeamethodsuchascharAttoindexanarray.Instead,wesimplyenclosetheindexwithinsquarebrackets.Thusthe1stelementofnamesis:names[0]andthenthelementisnames[n-1]Thesizeofthearrayisgivenby:names.lengthThelegalindicesofthearray,thus,are:0..names.length-1Ifweuseanindexthatisnotinthisrange,JavawillraiseanArrayIndexOutOfBoundsException.Notethatunlikethecaseofastring,lengthisnotaninstancemethod,andthusisnotfollowedbyparentheses.Instead,itisessentiallyapublicinstancevariableofthearray.Thoughwecanreadthevalueofthisvariable,wecannotassigntoit,becausethesizeofanarrayisfixedduringitslifetime.Itshouldberegardedasaspecialinstancevariableofanarraythatcannotbemodifiedafterithasbeenassignedthefirsttime.UninitializedArrayElementsUnlikeastring,anarraycanbemodified.Forinstance,thefollowingstatement:names[0]=“JohnnySmith”assignsanewvaluetothefirstelementofthearray.Recallthatitisnotpossibletosimilarlymodifyanelementofastring.Infact,whenanarrayiscreated,typically,wedonotknowwhatthevaluesofitselementswouldbe.Often,aswewillseelater,theyareassignedbasedontheuserinput.Therefore,Javaallowsustocreateanarraywithuninitializedelements.Forinstance,theexpression:newLoan[MAX_LOANS]createsanewloanarrayofsizeMAX_LOANSwhoseelementsareuninitialized.SincethesizeofaJavaarrayisfixedduringitslifetime,whenitiscreated,wemusttellJavahowmanyelementsithas,evenifwedonotknowthenwhatthevaluesoftheseelementswillbe.Thus,thesquarebracketsafteranelementtypemustencloseasizeordimensionwhenanarrayinstanceiscreated,sincetheinstanceisfixed-size,butnotwhenanarraytypeisspecified,sincethetypeisvariable-sized.Anarraywithuninitializedelementscanbeusedtoinitializeanarrayvariable:Loan[]loans=newLoan[MAX_LOANS];Here,thearrayvariable,loans,isinitializedwithanarrayofsizeMAX_LOANS.ThismeansthatthevalueofthevariableisacollectionofMAX_LOANSslotsthatcanstorevaluesoftypeLoan.However,theseslotsarethemselvesuninitialized,thatis,havenovaluesassignedtothem.Later,wecaninitializethem:loans[0]=newALoan(2,3);loans[1]=newAnotherLoan(3,1);Thus,thinkofthearrayelements,loans[0]andloans[1],asthemselvesvariables,whichshouldbeinitializedbeforeaccessingtheirvalues.FigureSEQFigure\*ARABICFigureSEQFigure\*ARABIC1.anuninitializedloan-arrayvariable,loansFigureSEQFigure\*ARABIC2.aninitializedloan-arrayvariable,loans,withfirsttwoelementsinitializedandtherestuninitializedArraysmustoftenbecreatedwithuninitializedarrayelements.Thereisthedanger,thus,ofaccidentallyaccessinganuninitializedarrayelement.Whatexactlyhappenswhenwetryandaccessanuninitializedarrayelement?Actually,letustryandanswerthemoregeneralquestion:Whatexactlyhappenswhenwetryandaccessanyuninitializedvariable?Therearethreecases:Compilererror:ifthevariableisalocalvariable,thenthecompilerflagssuchanaccessasanerror,andrefusestogenerateexecutablecode.Defaultvalue:ifthevariableisaglobal(classorinstance)primitive-variable,thenadefaultvalueofthetypeisstoredinthevariable.Thereforewhenweaccessthisvariable,wegetthisvalue.Thedefaultvalue,inthecaseofnumerictypes,is0,andinthecaseofotherprimitivetypes,isavaluewhosecomputerencodingis0.Thismeansinthecaseofchar,itisthenullcharacter,andinthecaseofboolean,itisfalse.Specialvalue:ifthevariableisaglobalobject-variable,Javadoesnotstoreadefaultobjectofthattype.Instead,itstoresaspecialvalue,callednull.Ifwetryandaccessthevariable,wegetaNullPointerException.Bewareofthisexception-itisveryeasytowriteprogramsthataccessuninitializedobjectvariables!Thefirstapproachofgeneratingacompilererrorseemsthebestbecausebeforeweevenruntheprogramwearetoldaboutthemistake.WhydoesJavanotuseitalsoforglobalvariables?Thereasonisthatthesecanbeaccessedbymultiplemethods,anditisdifficult,andsometimesimpossible,toknow,whencompilingaclass,whetherthesevariableshavebeeninitializedbeforeaccess.Whyusedifferentapproachesforprimitiveandobjectglobalvariables,andwhichapproachisbetter?Theapproachofstoringaspecialvalueisprobablybetterbecauseitallowstheprogramtoknow(atFigureSEQFigure\*ARABICFigureSEQFigure\*ARABIC3.Afixed-sizecollectionLetusreturntoarrayvariables,andbetterunderstandwhatitmeansforthemtobeuninitialized.REF_Ref182572122\hFigure1andREF_Ref182572124\hFigure2illustratethetwoformsofuninitializationinaprogramwitharrays.REF_Ref182572122\hFigure1,thearray,loans,itselfisuninitialized.InREF_Ref182572124\hFigure2,thearrayisinitialized,butits3rdand4thelementsareuninitialized.Thus,ifyougetaNullPointerExceptioninaprogramthatusesarrays,youmayhaveforgottentoinitializeeitheranarrayvariableoranarrayelement.Fixed-SizeCollectionsArrayscanbeusedtoimplementavarietyofcollectionssuchasdatabases,histories,sets,andorderedlists.Considertheimplementationofasimple,fixed-size,databaseshowninREF_Ref182572208\hFigure3.Itcollectsaseriesofinputstringsenteredbytheuser,andprintsthemonrequest.Thenumberofstringsinthecollectionisspecifiedbeforethefirstelementisinput.Wehavedoneproblemsbeforethatprocessedalistofitemssuchastheproblemofcomputingthesumofalistofinputnumbers.Wedidthoseproblemswithoutusingarrays;sowhydoweneedarrayshere?Inthepreviousproblems,afterthesequenceofinputvalueswasprocessed,itwasnotneededagain.Thisisnotthecasehere,becausewemightwanttoprinttheinputvaluesmultipletimes.Therefore,thevaluesmustbestoredinmemoryinsomevariable.Thetypeofthevariablecannotdefineafixed-sizebecausethenumberofelementsinthecollectionisspecifiedatruntime.Theonlyvariable-sizetypeswehaveseensofarareStringandthearraytypes.Sincetheitemsbeingcollectedarestringsandnotcharacters,weshouldusethearraytype,String[],asthetypeofthecollection.Wearenowreadytogivethetop-levelofouralgorithm.Thislevelinvokesmethodstogetaninstanceofthedatabasetypeandprintit:publicstaticvoidmain(String[]args){String[]names=getStrings();Stringcommand=Console.readString();while(command.length()>0&&command.charAt(0)!='q'){if(command.charAt(0)=='p')//printdatabaseifuserenters‘p’print(names);Stringcommand=Console.readString();}}ThemainmethodfirstcallsgetStrings,whichreturnsthelistoflinesenteredbytheuserasastringarray.Theprogramassignsthisvaluetothestringarray-variable,names.Itthenprocesseseachcommandstringenteredbytheuser.Ifthestringis:thequitcommand,thatis,thefirstcharacterofthestringis‘q’,thentheprogramterminates.theprintcommand,thatis,thefirstcharacterofthestringis‘p’,thentheprogramcallstheprintmethodtoprintthestring-arraycollection.anyotherstringtheprogramsimplyignoresit.Beforelookingatthefirstcharacterofthecommand,theprogramchecksthatithasatleastonecharacter.Itispossibleforittohavenocharacters–iftheuserpressestheEnterkeywithoutenteringanythingintheline,thenthereadStringmethodreturnsthenullstring.Ifthelengthcheckisnotmade,thentheJavawillthrowaStringIndexBoundsexceptionifwetrytoaccessthefirstcharacterofanullstring.Tocompletethisimplementation,wemustdefinetheprintandgetStringsmethods.ProcessingArraysofDifferentSizesThemethod,print,simplyprintsallelementsofitsargument.Sincetheargumentcanbeastringarrayofarbitrarysize,itusesthelengthvariabletodeterminehowmanyelementsthereare:MethodssuchasthisonethataccessarraysofdifferentsizeswerenotpossibleinlanguagessuchasPascalwithfixed-sizearraytypes.Insuchlanguages,wewouldneedaseparatemethodforeacharray-size.Thus,weseehereanimportantbenefitofvariable-sizedarraytypes.MethodssuchasthisonethataccessarraysofdifferentsizeswerenotpossibleinlanguagessuchasPascalwithfixed-sizearraytypes.Insuchlanguages,wewouldneedaseparatemethodforeacharray-size.Thus,weseehereanimportantbenefitofvariable-sizedarraytypes.staticvoidprint(String[]strings){System.out.println("******************");for(intelementNum=0;elementNum<strings.length;elementNum++)System.out.println(strings[elementNum]);System.out.println("******************");}RuntimeArray-SizeThemethod,getStrings,isadualofprint.Insteadofreceivinganarrayasanargumentfromitscaller,itreturnsanarraytoitscaller.staticString[]getStrings(){System.out.println("NumberofStrings:");intnumElements=Console.readInt();System.out.println("Pleaseenter"+numElements+"strings");String[]strings=newString[numElements];for(intelementNum=0;elementNum<numElements;elementNum++)strings[elementNum]=Console.readString();returnstrings;}Itreadsthenumberofelementsenteredbytheuser,andusesthisvalueinString[]strings=newString[numElements];tocreateanarrayoftherightsize.Asweseehere,thearraydimensionspecifiedinnewdoesnothavetobeaconstant.Eventhoughanarrayisafixed-sizedinstance,thesizeisnotdeterminedatcompiletime.Itisdeterminedwhenthearrayisinstantiated.Afterinstantiatingthearray,thismethodstoreseachinputvalueinthearrayandreturnswhenthearrayiscompletelyfull.Itdoesnotaccessthelengthfieldofthearraysinceitknowsthearraysize(storedinnumElements)havingcreatedthearrayitself.FigureSEQFigure\*ARABICFigureSEQFigure\*ARABIC4.Avariable-sizecollectionFigureSEQFigure\*ARABIC5.Letusconsideramoreinterestingvariationoftheproblemabove,showninREF_Ref182572481\hFigure4.Inthisproblem,usersdonotspecifythenumberofcollectionelementsatthestartoftheinteraction.Theykeepenteringstringsuntiltheyquittheprogram.Moreover,theydonothavetowaitfortheentiredatabasetobeenteredbeforeprintingit.Theycanprintthedatabaseafterasubsetofithasbeenentered.Thisisamorecomplicatedproblem.Asbefore,wemustcollectthestringsinmemorysothattheycanbeprintedmultipletimes.Butaftertheyhavebeenprinted,ausercanenteradditionalitems.Thus,weneedtocreateacollectioninmemorythatcangrowdynamically.Itis,infact,possibletouseafixed-sizearraytostoreavariable-sizecollection,muchaswewritevariable-sizedlistsinfixed-sizepages.Asthefollowingfigureillustrates,suchacollectioncanbesimulatedusinganarrayandtwointvariables.Thesizeofthearrayisthemaximumsizeofthecollection,givenbyoneoftheintvariables.Thefilledpartconsistsofelementsofthevariable-sizedcollectionandtheunfilledpartconsistsoftheunusedelementsofthearray.Thesizeofthefilledpart,thus,rangesfrom0tothearraylength.Westorethisvalueinthesecondintvariable,andupdateitwheneverweaddordeleteacollectionelement.Thus,changingthesizeofthecollectioninvolveschangingtheboundarybetweenthefilledandunfilledpartsofthearray.Sincethelengthofanarraycannotchangeonceithasbeeninstantiated,the“variable”storingthevalueofthemaximumsizeofthecollectionisusuallydeclaredasfinaltomakeitreadonly.EncapsulatingRelatedVariablesItisconsideredgoodprogrammingpracticetorelatethenamesofthethreevariablesdefiningthevariable-sizedcollection.Thepopularapproach(usedinmosttextbooks)istodeclarethesevariablesintheclassthatneedsthecollection,andnamethecurrentandmaximumsizevariablesaSize,andA_MAX_SIZE,respectively,ifthearrayisnameda.finalintA_MAX_SIZE=50;String[]a=newString[A_MAX_SIZE];intaSize=0;//processcollectiona…Iftheclassneedsanothercollectionofthiskind,itsimilarlycreatesanotherthreevariables:finalintB_MAX_SIZE=50;String[]b=newString[B_MAX_SIZE];intbSize=0;//processcollectionb…Wecan,infact,dobetterthanthis,sinceeachtimeweneedagroupofrelatedvariables,weshoulddeclarethemasinstancevariablesofanewclass.Hereisonewayofdoingso:publicclassAVariableSizedStringCollection{publicfinalintMAX_SIZE=50; publicString[]contents=newString[MAX_SIZE]; publicintsize=0;}Inthisdeclaration,thethreevariablesaredeclaredaspublicinstancevariablesoftheclass.Eachtimeweneedanewdynamiccollectionofstrings,wecancreateanewinstanceofthisclassandstoreitinsomevariable:AVariableSizedStringCollectiona=newAVariableSizedStringCollection();AVariableSizedStringCollectionb=newAVariableSizedStringCollection();Wecanthenrefertothearrayandsizecomponentsofit,asshownbelow:a.MAX_SIZEa.contentsa.sizeb.MAX_SIZE….Thisapproachissuperiortocreatingseparatevariables,suchasaSizeanda,becauseitcreatesanewtypethatbettermatchestheproblemthantheseparatearrayandinttypesdoindividually.Asaresult,itgivesustheadvantagesofdefininghigh-leveltypessuchasreuseofthedeclarationsdefiningthevariablesizecollectionandallowingadynamiccollectiontobereturnedbyafunction.However,itdoesnotmeettheprincipleofleastprivilege.Becauseboththenon-finalinstancevariableshavebeendeclaredpublic,usersofthisclasscanmanipulatetheminarbitraryways.Forinstance,theycanaddanewelementtothearraywithoutincrementingthesizefield;ormakethesizefieldbecomelargerthanMAX_SIZE.HistoryTherefore,weshouldencapsulatethevariables,thatis,makethemnon-publicandprovideaccesstothemthroughpublicmethods.Thesemethodsdependonthenatureofthecollectionwewant.IntheproblemofFigure5,weneedoperationsto:addanelementtothecollection,examineeachelementofthecollectionsothatwecanprintit.Wedonotneedoperationstomodifyordeleteelements.Thus,thecollectionweneedisreallyahistoryofstrings–asinthecaseofahistoryofpastevents,itsfilledportioncannotbeoverwritten.Thefollowinginterfacedefinestheseoperations:publicinterfaceStringHistory{publicvoidaddElement(Stringelement);publicStringelementAt(intindex);publicintsize();}LikeString,theinterfaceprovidesamethodtoaccessanelementataparticularindex.Itis,ofcourse,moreconvenienttoindexacollectionlikeanarrayusingthesquarebrackets,[and].Unfortunately,inJava,suchindexingcannotbeusedforprogrammer-definedtypes,requiringspecialsupportfromtheprogramminglanguage.LikeString,thisinterfacealsoprovidesamethodtofindthesizeofthecollection.Finally,unliketheimmutableString,itprovidesamethodtoaddanelementtothecollection.Thethreevariablescreatingavariable-sizestorageforthehistoryelementsaredefined,notintheinterface,butinitsimplementation,AStringHistory:publicclassAStringHistoryimplementsStringHistory{publicfinalintMAX_SIZE=50;String[]contents=newString[MAX_SIZE];intsize=0;publicintsize(){returnsize;}publicStringelementAt(intindex){returncontents[index];}booleanisFull(){returnsize==MAX_SIZE;}publicvoidaddElement(Stringelement){if(isFull())System.out.println("Addingitemtoafullhistory");else{contents[size]=element;size++;}}}UnlikeAVariableStringCollection,AStringHistorydoesnotmaketheseinstancevariablespublic.Asaresult,itsupportsencapsulation–allaccesstothesevariablesisthroughthepublicmethodsoftheclass.Asaresult,thereisnodangerthesevariableswillbemanipulatedinaninconsistentmannerfromoutsidetheclass.Moreover,ifweweretochangethevariablesby,forinstance,renamingthem,increasingthemaximumsize,orreplacinganarraywithanotherdatastructure(suchasVector,discussedlater),theusersoftheclasswouldnotknowthedifferenceandthuscouldbereusedwiththenewimplementation.Mostofthemethodsofthisclassaretrivial.Themethodsizereturnsthecurrentsize,elementAtindexesthearraytoreturnitsresult,andisFullreturnstrueifthecurrentsizehasreacheditsmaximumvalue.ThemethodaddElementrequiressomethought.Ifthecollectionisnotfull,thevalueofsizeistheindexofthefirstelementoftheunfilledpartofthearray.Inthiscase,itsimplyassignstothiselementthenewvalue,andincrementssize.Thetrickyissuehereiswhatshouldhappenwhenthecollectionisfull?Ifwehaveguessedthemaximumsizeright,thisconditionshouldnotarise.Nonetheless,wemustdecidehowtohandlethissituation.Somechoicesare:SubscriptException:Wecouldignorethissituation,andletJavathrowanArrayIndexOutOfBoundsExceptionwhenthemethodaccessesthearraybeyondthelastelement.However,thismaynotbeveryilluminatingtotheuser,whomaynotknowthattheimplementationusesanarray(ratherthan,say,avector,discussedlater).SpecializedException:Wecoulddefineaspecialexceptionforthissituation,CollectionIsFullException,andthrowit.However,definingnewexceptionsisbeyondthescopeofthiscourse.PrintMessage:Wewouldprintamessagefortheuser.Unfortunately,thecallerofaddElementgetsnofeedbackwiththismessage.IncreaseSize:Ifitisnotanerrortoaddmoreelementsthantheoriginalarraycanaccommodate,wecouldincreasethesizeofthecollectionbycreatingalargerarray,addalltheelementsofthepreviousarraytoit,andassignthenewarraytothecontentsfield.Ourprogramassumesitisanerrortoaddtoafullcollectionandsimplyprintsamessage.Asthediscussionabovepointsout,hadweknownhowtodefineone,aspecializedexceptionwouldhavebeenabetteralternativeunderthisassumption.ThefollowingmainmethodillustrateshowStringHistoryanditsimplementationAStringHistory,areusedtosolveourproblem:publicstaticvoidmain(String[]args){StringHistorynames=newAStringHistory();//createanemptyhistorywhile(true){Stringinput=Console.readString();if(input.length>0)if(input.charAt(0)=='q')//exitloopifuserenters‘q’break;elseif(input.charAt(0)=='p')//printdatabaseifuserenters‘p’print(names);else//addinputtohistorynames.addElement(input);}}Itismuchlikethemainweusedforthefixed-sizecollectionwithtwomaindifferences.InsteadofthearraytypeString[],itusesournewtypeStringHistory.Second,insteadofgatheringalldatabaseentriesbeforestartingthecommandloop,itgathersdatabaseentriesincrementallyintheloop.Ifanon-nullinputlinedoesnotbeginwithanyoftherecognizedcommands,theloopassumesitisadatabaseentry,andcallstheaddElementmethodtoaddittotheStringHistoryinstance.FigureSEQFigure\*ARABIC6.AddElementofAPointHistoryFigureSEQFigure\*ARABICFigureSEQFigure\*ARABIC6.AddElementofAPointHistoryFigureSEQFigure\*ARABIC7.APointHistorywith5pointsstaticvoidprint(StringHistorystrings){System.out.println("******************");for(intelementNum=0;elementNum<strings.size();elementNum++)System.out.println(strings.elementAt(elementNum));}DatabaseAhistoryisperhapsthesimplestexampleofavariable-sized

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论