资源描述:
《论文翻译(原文)》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、JavaPuzzlers:Traps,Pitfalls,andCornerCasesJava™Puzzlers:Traps,Pitfalls,andCornerCasesByJoshuaBloch,NealGafterPublisher:AddisonWesleyProfessionalPubDate:June24,2005ISBN:0-321-33678-XPuzzle1:OddityThefollowingmethodpurportstodeterminewhetheritssoleargumentisanoddnumber.Doest
2、hemethodwork?publicstaticbooleanisOdd(inti){returni%2==1;Solution1:OddityAnoddnumbercanbedefinedasanintegerthatisdivisibleby2witharemainderof1.Theexpressioni%2computestheremainderwheniisdividedby2,soitwouldseemthatthisprogramoughttowork.Unforturmtcly,itdocsn"t;itrcturnsthe
3、wrongansweronequarterofthetime.Whyonequarter?Becausehalfofallintvaluesarenegative,andtheisOddmethodfailsforallnegativeoddvalues.Itreturnsfalsewheninvokedonanynegativevalue,whetherevenorodd.ThisisaconsequenceofthedefinitionofJava'sremainderoperator(%)•Itisdefinedtosatisfyth
4、efollowingidentityforallintvaluesaandallnonzerointvaluesb:(a/b)*b+(a%b)==aInotherwords,ifyoudivideabyb,multiplytheresultbyb,andaddtheremainder,youarebackwhereyoustarted[JLS15.17.3].Thisidentitymakesperfectsense,butincombirmtionwithJava'strimcatingintegerdivisionoperator[JL
5、S15.17.2],itimpliesthatwhentheremainderopcrationrcturnsanonzcroresult,ithasthesamesignasitsleftoperand.TheisOddmethodandthedefinitionofthetermoddonwhichitwasbasedbothassumethatal1remaindersarepositive.Althoughthisassumptionmakessenseforsomekindsofdivision[Boxing],Java'srem
6、ainderoperationispcrfcctlymatchedtoitsintegerdivisionoperation,whichdiscardsthefractionalpartofitsresult.Wheniisanegativeoddnumber,i%2isequalto-1ratherthan1,sotheisOddmethodincorrectlyreturnsfalse.Topreventthissortofsurprise,testthatyourmethodsbehaveproperlywhenpassednegat
7、ive,zero,andpositivevaluesforeachnumericalparameter.Theproblemiseasytofix.Simplycomparei%2to0ratherthanto1,andreversethesenseofthecomparison:publicstaticbooleanisOdd(inti)returni%2!=0;IfyouareusingtheisOddmethodinaperformance-criticalsetting,youwouldbebetteroffusingthebitw
8、iseANDoperator(&)inplaceoftheremainderoperator:publicstaticbooleanisOdd(inti){return(i&1)