thinking injava习题答案8.docx
- 文档编号:23850440
- 上传时间:2023-05-21
- 格式:DOCX
- 页数:133
- 大小:55.92KB
thinking injava习题答案8.docx
《thinking injava习题答案8.docx》由会员分享,可在线阅读,更多相关《thinking injava习题答案8.docx(133页珍藏版)》请在冰豆网上搜索。
thinkinginjava习题答案8
这是第9章的答案:
Chapter9
Tocompileandexecutetheseprograms,you’llneedtodownloadandinstallthecodetreefromThinkinginJava,2ndEditionfromwww.BruceE,andyou’llneedtoputthefullpathofthebasedirectoryofthecodetree(named‘code’)intoyourclasspath.
Exercise1
//:
c09:
E01_RandDouble.java
//+MjavaE01_RandDouble
/******************Exercise1******************
*Createanarrayofdoubleandfill()itusing
*RandDoubleGenerator.Printtheresults.
***********************************************/
importcom.bruceeckel.util.Arrays2;
publicclassE01_RandDouble{
publicstaticvoidmain(Stringargs[]){
double[]da=newdouble[10];
Arrays2.fill(da,
newArrays2.RandDoubleGenerator());
Arrays2.print(da);
}
}///:
~
Thisissimplyanexerciseinusingthegeneratorfromthepackage.
Theoutputforonerunis:
(0.5001203986291445,0.8539982462192328,
0.6726664848706867,0.892650339160878,
0.6006173265811632,0.6156735136224198,
0.6478510992181377,0.5858583665142717,
0.8760917695678225,0.5931881088554638)
Exercise2
//:
c09:
E02_Gerbil.java
//+MjavaE02_Gerbil
/******************Exercise2******************
*CreateanewclasscalledGerbilwithanint
*gerbilNumberthat'sinitializedinthe
*constructor(similartotheMouseexamplein
*thischapter).Giveitamethodcalledhop()
*thatprintsoutwhichgerbilnumberthisis,
*andthatit'shopping.CreateanArrayListand
*addabunchofGerbilobjectstotheList.Now
*usetheget()methodtomovethroughtheList
*andcallhop()foreachGerbil.
***********************************************/
importjava.util.*;
classGerbil{
privatestaticintgerbilCounter=0;
privateintgerbilNumber=++gerbilCounter;
publicStringtoString(){
return"gerbil"+gerbilNumber;
}
publicvoidhop(){
System.out.println(toString()
+"ishopping");
}
}
publicclassE02_Gerbil{
publicstaticvoidmain(Stringargs[]){
ArrayListgerbils=newArrayList();
for(inti=0;i<10;i++)
gerbils.add(newGerbil());
for(inti=0;i ((Gerbil)gerbils.get(i)).hop(); } }///: ~ Theoutputis: gerbil1ishopping gerbil2ishopping gerbil3ishopping gerbil4ishopping gerbil5ishopping gerbil6ishopping gerbil7ishopping gerbil8ishopping gerbil9ishopping gerbil10ishopping Exercise3 //: c09: E03_GerbilIterator.java //+MjavaE03_GerbilIterator /******************Exercise3****************** *ModifyExercise2soyouuseanIteratorto *movethroughtheListwhilecallinghop(). ***********************************************/ importjava.util.*; publicclassE03_GerbilIterator{ publicstaticvoidmain(Stringargs[]){ ArrayListgerbils=newArrayList(); for(inti=0;i<10;i++) gerbils.add(newGerbil()); for(Iteratorit=gerbils.iterator(); it.hasNext();) ((Gerbil)it.next()).hop(); } }///: ~ Thisproducesthesameoutputasbefore. Exercise4 //: c09: E04_GerbilMap.java //+MjavaE04_GerbilMap /******************Exercise4****************** *TaketheGerbilclassinExercise2andputit *intoaMapinstead,associatingthenameof *theGerbilasaString(thekey)foreach *Gerbil(thevalue)youputinthetable.Get *anIteratorforthekeySet()anduseitto *movethroughtheMap,lookinguptheGerbil *foreachkeyandprintingoutthekeyand *tellingthegerbiltohop(). ***********************************************/ importjava.util.*; publicclassE04_GerbilMap{ publicstaticvoidmain(Stringargs[]){ HashMapmap=newHashMap(); map.put("Bob",newGerbil()); map.put("Frank",newGerbil()); map.put("Tiffany",newGerbil()); map.put("Ted",newGerbil()); map.put("Wallace",newGerbil()); map.put("Heather",newGerbil()); Iteratorit=map.keySet().iterator(); while(it.hasNext()){ Stringkey=(String)it.next(); Gerbilvalue=(Gerbil)map.get(key); System.out.println("name="+key +",value="+value); } } }///: ~ Theoutputis: name=Frank,value=gerbil2 name=Bob,value=gerbil1 name=Wallace,value=gerbil5 name=Ted,value=gerbil4 name=Tiffany,value=gerbil3 name=Heather,value=gerbil6 Notethattheobjectsarenotstoredintheorderthattheywereentered,becauseofthenatureofthehashingfunction(describedinthebook).IfyouuseaTreeMapinstead,you’llseethattheorderismaintained. Exercise5 //: c09: E05_CountryList.java //+MjavaE05_CountryList /******************Exercise5****************** *CreateaList(trybothArrayListand *LinkedList)andfillitusing *Collections2.countries.Sortthelistand *printit,thenapplyCollections.shuffle()to *thelistrepeatedly,printingiteachtimeso *thatyoucanseehowtheshuffle()method *randomizesthelistdifferentlyeachtime. ***********************************************/ importcom.bruceeckel.util.*; importjava.util.*; publicclassE05_CountryList{ publicstaticvoidmain(Stringargs[]){ Listlst=newArrayList(); Collections2.fill(lst, Collections2.countries,8); Collections.sort(lst); System.out.println(lst); for(inti=0;i<5;i++){ Collections.shuffle(lst); System.out.println(lst); } } }///: ~ IonlydiditforArrayList.Youcaneasilychangeit(inonlyoneplace)forLinkedList. Here’stheoutputfromonerun: [ALGERIA,ANGOLA,BENIN,BOTSWANA,BURKINAFASO,BURUNDI,CAMEROON,CAPEVERDE] [BENIN,ANGOLA,ALGERIA,CAPEVERDE,BURUNDI,CAMEROON,BOTSWANA,BURKINAFASO] [ALGERIA,BURKINAFASO,CAPEVERDE,BURUNDI,BOTSWANA,BENIN,ANGOLA,CAMEROON] [BENIN,ALGERIA,CAPEVERDE,CAMEROON,ANGOLA,BOTSWANA,BURUNDI,BURKINAFASO] [BOTSWANA,BURKINAFASO,ALGERIA,CAMEROON,CAPEVERDE,BURUNDI,ANGOLA,BENIN] [ALGERIA,BENIN,BOTSWANA,BURKINAFASO,BURUNDI,CAPEVERDE,CAMEROON,ANGOLA] Exercise6 //: c09: E06_MouseListRestriction.java //+MjavaE06_MouseListRestriction /******************Exercise6****************** *Demonstratethatyoucan'taddanythingbuta *MousetoaMouseList. ***********************************************/ importjava.util.*; classMouse{ privateintmouseNumber; Mouse(inti){mouseNumber=i;} //OverrideObject.toString(): publicStringtoString(){ return"ThisisMouse#"+mouseNumber; } publicintgetNumber(){ returnmouseNumber; } } classMouseList{ privateArrayListlist=newArrayList(); publicvoidadd(Mousem){ list.add(m); } publicMouseget(intindex){ return(Mouse)list.get(index); } publicintsize(){returnlist.size();} } publicclassE06_MouseListRestriction{ publicstaticvoidmain(Stringargs[]){ MouseListml=newMouseList(); //Compile-timeerror: notaMouse //! ml.add(newObject()); } }///: ~ Exercise7 //: c09: E07_MouseListProblem.java //+MjavaE07_MouseListProblem /******************Exercise7****************** *ModifyMouseList.javasothatitinheritsfrom *ArrayListinsteadofusingcomposition. *Demonstratetheproblemwiththisapproach. ***********************************************/ importjava.util.*; classMouseList2extendsArrayList{ publicvoidadd(Mousem){ System.out.println("Addingamouse"); super.add(m); } //Can'toverridewithdifferentreturntype: //! publicMouseget(inti){ //! return(Mouse)super.get(i); //! } //Sidestep: publicMousegetMouse(inti){ return(Mouse)super.get(i); } } publicclassE07_MouseListProblem{ publicstaticvoidmain(Stringargs[]){ MouseList2mice=newMouseList2(); for(inti=0;i<3;i++) mice.add(newMouse(i)); for(inti=0;i System.out.println(mice.getMouse(i)); //Oops! Canaddanon-mouse: mice.add(newObject()); } }///: ~ Thecompilerdetectsaproblemwhentryingtooverrideget()becausetheonlythingthat’sdifferentisthereturnvalue.Wecan“cleverly”sidestepthisbymakingagetMouse()method.However,notethattheArrayList.get()methodisstillaliveandwell,soit’sstillpossibletopullobjectsoutthroughthatchannel. Here’stheoutput: Addingamouse Addingamouse Addingamouse ThisisMouse#0 ThisisMouse#1 ThisisMouse#2 NotethattheObjectdoesnotcausean“Adding...”messagetobeprinted,becausetheadd()methodisactuallyoverloadingratherthanoverriding,whichmeansthattheadd(Object)methodstillexists,andiscalledinthelastcase.InheritingfromArrayListthusdoesnotlimitthetypeofobjectsthatcanbeadded,andsoitdefinitelyisn’twhatwewant.Andwithanon-Mouseinthelist,whenyoucallgetMouse()withthatobjectanexceptionwillbethrownduringthecast. Exercise8 //: c09: E08_RepairCatsAndDogs.java //+MjavaE08_RepairCatsAndDogs /******************Exercise8****************** *RepairCatsAndDogs.javabycreatingaCats *container(utilizingArrayList)thatwillonly *acceptandretrieveCatobjects. ***********************************************/ importjava.util.*; classCat{ privateintcatNumber; Cat(inti){catNumber=i;} voidprint(){ System.out.println("Cat#"+catNumber); } } classDog{ privateintdogNumber; Dog(inti){dogNumber=i;} voidprint(){ System.out.println("Dog#"+dogNumber); } } classCatContainer{ privateArrayListcats=newArrayList(); publicvoidadd(Catc){cats.add(c);} publicCatget(inti){ return(Cat)cats.get(i); } publicintsize(){returncats.size();} } publicclassE08_RepairCatsAndDogs{ publicstaticvoidmain(String[]args){ CatContainercats=newCatContainer(); for(inti=0;i<7;i++) cats.add(newCat(i)); //WillnotacceptaDog: //! cats.add(newDog(7)); for(inti=0;i
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- thinking injava习题答案8 injava 习题 答案
![提示](https://static.bdocx.com/images/bang_tan.gif)