|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
net程序员的大部门代码都靠控件拖拽完成的,虽然java也有,但是无论从美观和速度上都没发和.net比。java程序员都是代码完成的,所以java程序员常戏称.net程序员是操作员,呵呵。j2seAutoboxing
AsanyJavaprogrammerknows,youcan’tputanint(orotherprimitivevalue)intoacollection.Collectionscanonlyholdobjectreferences,soyouhavetoboxprimitivevaluesintotheappropriatewrapperclass(whichisIntegerinthecaseofint).Whenyoutaketheobjectoutofthecollection,yougettheIntegerthatyouputin;ifyouneedanint,youmustunboxtheIntegerusingtheintValuemethod.Allofthisboxingandunboxingisapain,andcluttersupyourcode.Theautoboxingandunboxingfeatureautomatestheprocess,eliminatingthepainandtheclutter.
Thefollowingexampleillustratesautoboxingandunboxing,alongwithgenericsandthefor-eachloop.Inameretenlinesofcode,itcomputesandprintsanalphabetizedfrequencytableofthewordsappearingonthecommandline.
importjava.util.*;//PrintsafrequencytableofthewordsonthecommandlinepublicclassFrequency{publicstaticvoidmain(String[]args){Map<String,Integer>m=newTreeMap<String,Integer>();for(Stringword:args){Integerfreq=m.get(word);m.put(word,(freq==null?1:freq+1));}System.out.println(m);}}javaFrequencyifitistobeitisuptometodothewatusi{be=1,do=1,if=1,is=2,it=2,me=1,the=1,to=3,up=1,watusi=1}
TheprogramfirstdeclaresamapfromStringtoInteger,associatingthenumberoftimesawordoccursonthecommandlinewiththeword.Thenititeratesovereachwordonthecommandline.Foreachword,itlooksupthewordinthemap.Thenitputsarevisedentryforthewordintothemap.Thelinethatdoesthis(highlightedingreen)containsbothautoboxingandunboxing.Tocomputethenewvaluetoassociatewiththeword,firstitlooksatthecurrentvalue(freq).Ifitisnull,thisisthefirstoccurrenceoftheword,soitputs1intothemap.Otherwise,itadds1tothenumberofprioroccurrencesandputsthatvalueintothemap.Butofcourseyoucannotputanintintoamap,norcanyouaddonetoanInteger.Whatisreallyhappeningisthis:Inordertoadd1tofreq,itisautomaticallyunboxed,resultinginanexpressionoftypeint.Sincebothofthealternativeexpressionsintheconditionalexpressionareoftypeint,sotooistheconditionalexpressionitself.Inordertoputthisintvalueintothemap,itisautomaticallyboxedintoanInteger.
TheresultofallthismagicisthatyoucanlargelyignorethedistinctionbetweenintandInteger,withafewcaveats.AnIntegerexpressioncanhaveanullvalue.Ifyourprogramtriestoautounboxnull,itwillthrowaNullPointerException.The==operatorperformsreferenceidentitycomparisonsonIntegerexpressionsandvalueequalitycomparisonsonintexpressions.Finally,thereareperformancecostsassociatedwithboxingandunboxing,evenifitisdoneautomatically.
Hereisanothersampleprogramfeaturingautoboxingandunboxing.ItisastaticfactorythattakesanintarrayandreturnsaListofIntegerbackedbythearray.InameretenlinesofcodethismethodprovidesthefullrichnessoftheListinterfaceatopanintarray.Allchangestothelistwritethroughtothearrayandvice-versa.Thelinesthatuseautoboxingorunboxingarehighlightedingreen:
//ListadapterforprimitiveintarraypublicstaticList<Integer>asList(finalint[]a){returnnewAbstractList<Integer>(){publicIntegerget(inti){returna[i];}//ThrowsNullPointerExceptionifval==nullpublicIntegerset(inti,Integerval){IntegeroldVal=a[i];a[i]=val;returnoldVal;}publicintsize(){returna.length;}};}
Theperformanceoftheresultinglistislikelytobepoor,asitboxesorunboxesoneverygetorsetoperation.Itisplentyfastenoughforoccasionaluse,butitwouldbefollytouseitinaperformancecriticalinnerloop.
Sowhenshouldyouuseautoboxingandunboxing?Usethemonlywhenthereisan“impedancemismatch”betweenreferencetypesandprimitives,forexample,whenyouhavetoputnumericalvaluesintoacollection.Itisnotappropriatetouseautoboxingandunboxingforscientificcomputing,orotherperformance-sensitivenumericalcode.AnIntegerisnotasubstituteforanint;autoboxingandunboxingblurthedistinctionbetweenprimitivetypesandreferencetypes,buttheydonoteliminateit.
用java开发web只要两本书:一本是关于java基础的,一本是关于jsp、servlet的就可以了。开发周期长,我就来讲句题外话,现在有很多思想都是通过java来展现。 |
|