版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
Chapter2Array2.1DeclaringandCreatingArrays2.4CopyingArrays2.2ArrayInitialize2.3Two-demensionArrays2.5PassingArraytomethods2021/7/131Chapter2Array2.1DeclariIntroducingArraysArrayisadatastructurethatrepresentsacollectionofthesametypesofdata.2021/7/132IntroducingArraysArrayisadDeclaringArrayVariablesdatatype[]arrayRefVar;
Example:double[]myList;datatypearrayRefVar[];//Thisstyleiscorrect,butnotpreferredExample:doublemyList[];inta[];=int[]a;int[]a,b;≠inta[],b;2021/7/133DeclaringArrayVariablesdatatCreatingArraysFormat:arrayRefVar=newdatatype[arraySize];Example:myList=newdouble[10];DefaultValue:Whenanarrayiscreated,itselementsareassignedthedefaultvalueof
0forthenumericprimitivedatatypes'\u0000'forchartypesfalseforbooleantypes2021/7/134CreatingArraysFormat:DefaultCreatingArrayse.g.:myList.lengthreturns10TheLengthofanArray:Onceanarrayiscreated,itssizeisfixed.Itcannotbechanged.Youcanfinditssizeusing
arrayRefVar.length2021/7/135CreatingArrayse.g.:myList.leusenewtocreat:c=newchar[5];
\u0000
\u0000
\u0000
\u0000
\u0000
50x1234(chararray,5chardata)cCreatingArrays2021/7/136usenewtocreat:\u0000\u00CreatingArray:referencedatatypeArray:Point[]p=newPoint[3];null
nullnull30x1245(PointArray,3Pointdata)pp[0]p[1]p[2]CreatingArrays2021/7/137CreatingArray:referencedataweshouldusenewtoallocatememoryforeveryelements.0,0p[0]0x1245p0,0null30x24640x2466p[1]p[0]=newPoint();p[1]=newPoint();CreatingArray:CreatingArrays2021/7/138weshouldusenewtoallocateDeclaringandCreatinginOneStepdatatype[]arrayRefVar=newdatatype[arraySize];e.g.:double[]myList=newdouble[10];datatypearrayRefVar[]=newdatatype[arraySize];e.g.:doublemyList[]=newdouble[10];2021/7/139DeclaringandCreatinginOne00030x4567ainta[]=newint[3];a[0]a[1]a[2]a.lengthExample:DeclaringandCreatinginOneStep2021/7/131000030x4567ainta[]=newArrayInitializeDeclaring,creating,initializinginonestep:e.g.:int[]a={1,2,3,4,5};String[]s={“abc”,“def”};String[]s={newString(“abc”),newString(“def”)};Thisshorthandsyntaxmustbeinonestatement.2021/7/1311ArrayInitializeDeclaring,credouble[]myList={1.9,2.9,3.4,3.5};Thisshorthandnotationisequivalenttothefollowingstatements:double[]myList=newdouble[4];myList[0]=1.9;myList[1]=2.9;myList[2]=3.4;myList[3]=3.5;
ArrayInitialize2021/7/1312double[]myList={1.9,2.9,3CAUTIONUsingtheshorthandnotation,youhavetodeclare,create,andinitializethearrayallinonestatement.Splittingitwouldcauseasyntaxerror.Forexample,thefollowingiswrong:double[]myList;myList={1.9,2.9,3.4,3.5};2021/7/1313CAUTIONUsingtheshorthandnotArrayInitialize:
Case:
ArrayClassObj.java
Case:
ArrayInit.javaArraysInitializeExample2021/7/1314ArrayInitialize:Case:Arimportjava.util.*;publicclassArrayClassObj{ staticRandomrand=newRandom(); staticintpRand(intmod){ returnMath.abs(rand.nextInt())%mod; } publicstaticvoidmain(String[]args){ Integer[]a=newInteger[pRand(20)]; prt("lengthofa="+a.length); for(inti=0;i<a.length;i++){ a[i]=newInteger(pRand(500)); prt("a["+i+"]="+a[i]); } } staticvoidprt(Strings){ System.out.println(s); }}ArrayClassObj.java2021/7/1315importjava.util.*;ArrayClassOpublicclassArrayInit{ publicstaticvoidmain(String[]args){ Integer[]a={ newInteger(1), newInteger(2), newInteger(3), };
//Java1.1only: Integer[]b=newInteger[]{ newInteger(1), newInteger(2), newInteger(3), }; }}2021/7/1316publicclassArrayInit{2021/7Two-dimensionalArraysDeclarearrayrefvar:dataType[][]refVar;e.g.:CreatearrayandassignitsreferencetovariablerefVar=newdataType[10][10];CombinedeclarationandcreationinonestatementdataType[][]refVar=newdataType[10][10];AlternativesyntaxdataTyperefVar[][]=newdataType[10][10];inta[][];int[]a[];int[][]a;2021/7/1317Two-dimensionalArraysDeclareTwo-dimensionalArrayIllustration2021/7/1318Two-dimensionalArrayIllustraTwo-dimensionalArraysLengthofTwo-dimensionalArrays:e.g.:int[][]x=newint[3][4];2021/7/1319Two-dimensionalArraysLengthoCaution:Accessinganarrayoutofboundsisacommonprogrammingerror,whichthrowsaruntimeArrayIndexOutOfBoundsException.Toavoidit,makesurethatyoudonotuseanindexbeyondarrayRefVar.length-1.Two-dimensionalArrays2021/7/1320Caution:Accessinganarrayouint[][]array={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};array.lengtharray[0].lengtharray[1].lengtharray[2].lengtharray[3].lengtharray[4].lengthArrayIndexOutOfBoundsExceptionTwo-dimensionalArraysExample:2021/7/1321int[][]array={array.lengthaCreating:【e.g.】int[][]a=newint[3][];null
nullnull30x4978aa[0]a[1]a[2]a.lengthTwo-dimensionalArrays2021/7/1322Creating:【e.g.】int[][]a=nnull
nullnull30x4978aa[0]a[1]a[2]a.lengtha=newint[3][];a[0]=newint[3];a[0][0]a[0][1]a[0][2]a[0].length0
0032021/7/1323nullnullnull30x4978aa[0]a[1]anull
nullnull30x4978aa[0]a[1]a[2]a.lengtha=newint[3][];a[0]=newint[3];a[1]=newint[2];a[0][0]a[0][1]a[0][2]a[0].length0
003002a[1][0]a[1][1]a[1].length2021/7/1324nullnullnull30x4978aa[0]a[1]anull
nullnull30x4978aa[0]a[1]a[2]a.lengtha=newint[3][];a[0]=newint[3];a[1]=newint[2];a[2]=newint[4];a[0][0]a[0][1]a[0][2]a[0].length0
003002a[1][0]a[1][1]a[1].lengtha[2][0]a[2][1]a[2][2]a[2][3]00004a[2].length2021/7/1325nullnullnull30x4978aa[0]a[1]aDeclaring,Creating,andInitializing
UsingShorthandNotationsYoucanalsouseanarrayinitializertodeclare,createandinitializeatwo-dimensionalarray.Forexample,int[][]array=newint[4][3];array[0][0]=1;array[0][1]=2;array[0][2]=3;array[1][0]=4;array[1][1]=5;array[1][2]=6;array[2][0]=7;array[2][1]=8;array[2][2]=9;array[3][0]=10;array[3][1]=11;array[3][2]=12;
int[][]array={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};Sameas2021/7/1326Declaring,Creating,andInitiEnhancedforLoopJDK1.5introducedanewforloopthatenablesyoutotraversethecompletearraysequentiallywithoutusinganindexvariable.
Ingeneral,thesyntaxis
Youstillhavetouseanindexvariableifyouwishtotraversethearrayinadifferentorderorchangetheelementsinthearray.for(elementTypevalue:arrayRefVar){//Processthevalue}
Arraytest.java2021/7/1327EnhancedforLoopJDK1.5introString[][]s=newString[10][];
a)Thislineofcodeisillegal.b)sisatwo-dimensionalarraycontaining10rowsand10columnsc)Eachelementinsissetto""d)Eachelementinsisuninitializedandmustbeinitializedbeforeitisreferenced.【Exercise】2021/7/1328String[][]s=newString[10CopyingArraysOften,inaprogram,youneedtoduplicateanarrayorapartofanarray.Insuchcasesyoucouldattempttousetheassignmentstatement(=),asfollows:
list2=list1;2021/7/1329CopyingArraysOften,inaprogCopyingArraysUsingaloop:int[]sourceArray={2,3,1,5,10};int[]targetArray=newint[sourceArray.length];for(inti=0;i<sourceArrays.length;i++)targetArray[i]=sourceArray[i];2021/7/1330CopyingArraysUsingaloop:202ThearraycopyUtilityarraycopy(sourceArray,src_pos,targetArray,tar_pos,length);Example:System.arraycopy(sourceArray,0,targetArray,0,sourceArray.length);2021/7/1331ThearraycopyUtilityarraycopyCopyingArray:System.arraycopy(object,int,object,int,int)inta[]={1,2,3};intb[]={4,5,6,7,8,9};
System.arraycopy(a,0,b,0,a.length);
b[]={1,2,3,7,8,9};Arraycopy.javaThearraycopyUtility2021/7/1332CopyingArray:Arraycopy.javaThPassingArraystoMethodspublicstaticvoidprintArray(int[]array){for(inti=0;i<array.length;i++){System.out.print(array[i]+"");}}Invokethemethodint[]list={3,1,2,6,4,2};printArray(list);InvokethemethodprintArray(newint[]{3,1,2,6,4,2});Anonymousarray2021/7/1333PassingArraystoMethodspubliAnonymousArrayThestatementprintArray(newint[]{3,1,2,6,4,2});createsanarrayusingthefollowingsyntax:
newdataType[]{literal0,...,literalk};Thereisnoexplicitreferencevariableforthearray.Sucharrayiscalledananonymousarray.
Case:
VarArgs.java2021/7/1334AnonymousArrayThestatementCclassA{inti;}publicclassVarArgs{ staticvoidf(Object[]x){ for(inti=0;i<x.length;i++) System.out.println(x[i]); } publicstaticvoidmain(String[]args){ f(newObject[]{ newInteger(47),newVarArgs(), newFloat(3.14),newDouble(11.11)}); f(newObject[]{"one","two","three"}); f(newObject[]{newA(),newA(),newA()}); }}VarArgs.java2021/7/1335classA{inti;}VarArgs.javaPassByValueJavausespassbyvaluetopassparameterstoamethod.Thereareimportantdifferencesbetweenpassingavalueofvariablesofprimitivedatatypesandpassingarrays.Foraparameterofaprimitivetypevalue,theactualvalueispassed.Changingthevalueofthelocalparameterinsidethemethoddoesnotaffectthevalueofthevariableoutsidethemethod.Foraparameterofanarraytype,thevalueoftheparametercontainsareferencetoanarray;thisreferenceispassedtothemethod.Anychangestothearraythatoccurinsidethemethodbodywillaffecttheoriginalarraythatwaspassedastheargument.2021/7/1336PassByValueJavausespassbypublicclassPassvalue{publicstaticvoidmain(String[]args){intx=1;//xrepresentsanintvalueint[]y=newint[10];//yrepresentsanarrayofintvalues
m(x,y);//Invokemwithargumentsxandy
System.out.println("xis"+x);System.out.println("y[0]is"+y[0]);}
publicstaticvoidm(intnumber,int[]numbers){number=1001;//Assignanewvaluetonumbernumbers[0]=5555;//Assignanewvaluetonumbers[0]}}SimpleExamplePassvalue.java2021/7/1337publicclassPassvalue{Simple問題?問題?Chapter2Array2.1DeclaringandCreatingArrays2.4CopyingArrays2.2ArrayInitialize2.3Two-demensionArrays2.5PassingArraytomethods2021/7/1339Chapter2Array2.1DeclariIntroducingArraysArrayisadatastructurethatrepresentsacollectionofthesametypesofdata.2021/7/1340IntroducingArraysArrayisadDeclaringArrayVariablesdatatype[]arrayRefVar;
Example:double[]myList;datatypearrayRefVar[];//Thisstyleiscorrect,butnotpreferredExample:doublemyList[];inta[];=int[]a;int[]a,b;≠inta[],b;2021/7/1341DeclaringArrayVariablesdatatCreatingArraysFormat:arrayRefVar=newdatatype[arraySize];Example:myList=newdouble[10];DefaultValue:Whenanarrayiscreated,itselementsareassignedthedefaultvalueof
0forthenumericprimitivedatatypes'\u0000'forchartypesfalseforbooleantypes2021/7/1342CreatingArraysFormat:DefaultCreatingArrayse.g.:myList.lengthreturns10TheLengthofanArray:Onceanarrayiscreated,itssizeisfixed.Itcannotbechanged.Youcanfinditssizeusing
arrayRefVar.length2021/7/1343CreatingArrayse.g.:myList.leusenewtocreat:c=newchar[5];
\u0000
\u0000
\u0000
\u0000
\u0000
50x1234(chararray,5chardata)cCreatingArrays2021/7/1344usenewtocreat:\u0000\u00CreatingArray:referencedatatypeArray:Point[]p=newPoint[3];null
nullnull30x1245(PointArray,3Pointdata)pp[0]p[1]p[2]CreatingArrays2021/7/1345CreatingArray:referencedataweshouldusenewtoallocatememoryforeveryelements.0,0p[0]0x1245p0,0null30x24640x2466p[1]p[0]=newPoint();p[1]=newPoint();CreatingArray:CreatingArrays2021/7/1346weshouldusenewtoallocateDeclaringandCreatinginOneStepdatatype[]arrayRefVar=newdatatype[arraySize];e.g.:double[]myList=newdouble[10];datatypearrayRefVar[]=newdatatype[arraySize];e.g.:doublemyList[]=newdouble[10];2021/7/1347DeclaringandCreatinginOne00030x4567ainta[]=newint[3];a[0]a[1]a[2]a.lengthExample:DeclaringandCreatinginOneStep2021/7/134800030x4567ainta[]=newArrayInitializeDeclaring,creating,initializinginonestep:e.g.:int[]a={1,2,3,4,5};String[]s={“abc”,“def”};String[]s={newString(“abc”),newString(“def”)};Thisshorthandsyntaxmustbeinonestatement.2021/7/1349ArrayInitializeDeclaring,credouble[]myList={1.9,2.9,3.4,3.5};Thisshorthandnotationisequivalenttothefollowingstatements:double[]myList=newdouble[4];myList[0]=1.9;myList[1]=2.9;myList[2]=3.4;myList[3]=3.5;
ArrayInitialize2021/7/1350double[]myList={1.9,2.9,3CAUTIONUsingtheshorthandnotation,youhavetodeclare,create,andinitializethearrayallinonestatement.Splittingitwouldcauseasyntaxerror.Forexample,thefollowingiswrong:double[]myList;myList={1.9,2.9,3.4,3.5};2021/7/1351CAUTIONUsingtheshorthandnotArrayInitialize:
Case:
ArrayClassObj.java
Case:
ArrayInit.javaArraysInitializeExample2021/7/1352ArrayInitialize:Case:Arimportjava.util.*;publicclassArrayClassObj{ staticRandomrand=newRandom(); staticintpRand(intmod){ returnMath.abs(rand.nextInt())%mod; } publicstaticvoidmain(String[]args){ Integer[]a=newInteger[pRand(20)]; prt("lengthofa="+a.length); for(inti=0;i<a.length;i++){ a[i]=newInteger(pRand(500)); prt("a["+i+"]="+a[i]); } } staticvoidprt(Strings){ System.out.println(s); }}ArrayClassObj.java2021/7/1353importjava.util.*;ArrayClassOpublicclassArrayInit{ publicstaticvoidmain(String[]args){ Integer[]a={ newInteger(1), newInteger(2), newInteger(3), };
//Java1.1only: Integer[]b=newInteger[]{ newInteger(1), newInteger(2), newInteger(3), }; }}2021/7/1354publicclassArrayInit{2021/7Two-dimensionalArraysDeclarearrayrefvar:dataType[][]refVar;e.g.:CreatearrayandassignitsreferencetovariablerefVar=newdataType[10][10];CombinedeclarationandcreationinonestatementdataType[][]refVar=newdataType[10][10];AlternativesyntaxdataTyperefVar[][]=newdataType[10][10];inta[][];int[]a[];int[][]a;2021/7/1355Two-dimensionalArraysDeclareTwo-dimensionalArrayIllustration2021/7/1356Two-dimensionalArrayIllustraTwo-dimensionalArraysLengthofTwo-dimensionalArrays:e.g.:int[][]x=newint[3][4];2021/7/1357Two-dimensionalArraysLengthoCaution:Accessinganarrayoutofboundsisacommonprogrammingerror,whichthrowsaruntimeArrayIndexOutOfBoundsException.Toavoidit,makesurethatyoudonotuseanindexbeyondarrayRefVar.length-1.Two-dimensionalArrays2021/7/1358Caution:Accessinganarrayouint[][]array={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};array.lengtharray[0].lengtharray[1].lengtharray[2].lengtharray[3].lengtharray[4].lengthArrayIndexOutOfBoundsExceptionTwo-dimensionalArraysExample:2021/7/1359int[][]array={array.lengthaCreating:【e.g.】int[][]a=newint[3][];null
nullnull30x4978aa[0]a[1]a[2]a.lengthTwo-dimensionalArrays2021/7/1360Creating:【e.g.】int[][]a=nnull
nullnull30x4978aa[0]a[1]a[2]a.lengtha=newint[3][];a[0]=newint[3];a[0][0]a[0][1]a[0][2]a[0].length0
0032021/7/1361nullnullnull30x4978aa[0]a[1]anull
nullnull30x4978aa[0]a[1]a[2]a.lengtha=newint[3][];a[0]=newint[3];a[1]=newint[2];a[0][0]a[0][1]a[0][2]a[0].length0
003002a[1][0]a[1][1]a[1].length2021/7/1362nullnullnull30x4978aa[0]a[1]anull
nullnull30x4978aa[0]a[1]a[2]a.lengtha=newint[3][];a[0]=newint[3];a[1]=newint[2];a[2]=newint[4];a[0][0]a[0][1]a[0][2]a[0].length0
003002a[1][0]a[1][1]a[1].lengtha[2][0]a[2][1]a[2][2]a[2][3]00004a[2].length2021/7/1363nullnullnull30x4978aa[0]a[1]aDeclaring,Creating,andInitializing
UsingShorthandNotationsYoucanalsouseanarrayinitializertodeclare,createandinitializeatwo-dimensionalarray.Forexample,int[][]array=newint[4][3];array[0][0]=1;array[0][1]=2;array[0][2]=3;array[1][0]=4;array[1][1]=5;array[1][2]=6;array[2][0]=7;array[2][1]=8;array[2][2]=9;array[3][0]=10;array[3][1]=11;array[3][2]=12;
int[][]array={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};Sameas2021/7/1364Declaring,Creating,andInitiEnhancedforLoopJDK1.5introducedanewforloopthatenablesyoutotraversethecompletearraysequentiallywithoutusinganindexvariable.
Ingeneral,thesyntaxis
Youstillhavetouseanindexvariableifyouwishtotraversethearrayinadifferentorderorchangetheelementsinthearray.for(elementTypevalue:arrayRefVar){//Processthevalue}
Arraytest.java2021/7/1365EnhancedforLoopJDK1.5introString[][]s=newString[10][];
a)Thislineofcodeisillegal.b)sisatwo-dimensionalarraycontaining10rowsand10columnsc)Eachelementinsissetto""d)Eachelementinsisuninitializedandmustbeinitializedbeforeitisreferenced.【Exercise】2021/7/1366String[][]s=newString[10CopyingArraysOften,inaprogram,youneedtoduplicateanarrayorapartofanarray.Insuchcasesyoucouldattempttousetheassignmentstatement(=),asfollows:
list2=list1;2021/7/1367CopyingArraysOften,inaprogCopyingArraysUsingaloop:int[]sourceArray={2,3,1,5,10};int[]targetArray=newint[sourceArray.length];for(inti=0;i<sourceArrays.length;i++)targetArray[i]=sourceArray[i];2021/7/1368CopyingArraysUsingaloop:202ThearraycopyUtilityarraycopy(sourceArray,src_pos,targetArray,tar_pos,length);Example:System.arraycopy(sourceArray,0,targetArray,0,sourceArray.length);2021/7/1369ThearraycopyUtilityarraycopyCopyingArray:System.arraycopy(object,int,object,int,int)inta[]={1,2,3};intb[]={4,5,6,7,8,9};
System.arraycopy(a,0,b,0,a.length);
b[]={1,2,3,7,8,9};Arraycopy.javaThearraycopyUtility2021/7/1370CopyingArray:Arraycopy.javaThPassingArraystoMethodspublicstaticvoidprintArray(int[]array){for(inti=0;i<array.length;i++){System.out.print(array[i]+"
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度新型環(huán)保技術(shù)合作承諾合同范本4篇
- 2025版智能社區(qū)門牌制作及管理系統(tǒng)集成合同4篇
- 二零二五版智能科技專利轉(zhuǎn)讓合同補充協(xié)議3篇
- 數(shù)據(jù)化辦公實驗室數(shù)據(jù)的處理與應(yīng)用
- 2025年度個人教育培訓(xùn)分期付款合同8篇
- 2025版協(xié)議書范本合同(環(huán)保產(chǎn)業(yè))2篇
- 長安大學(xué)《大學(xué)外語聽說》2023-2024學(xué)年第一學(xué)期期末試卷
- 2024鐵路電氣化區(qū)段安全使用合同3篇
- 家用醫(yī)療設(shè)備為殘疾人提供個性化的康復(fù)方案
- 現(xiàn)代家庭的沖突解決與情緒管理策略
- 2025年度杭州市固廢處理與資源化利用合同3篇
- 2024年安徽省公務(wù)員錄用考試《行測》真題及答案解析
- 部編版二年級下冊《道德與法治》教案及反思(更新)
- 充電樁項目運營方案
- 退休人員出國探親申請書
- 高中物理競賽真題分類匯編 4 光學(xué) (學(xué)生版+解析版50題)
- 西方經(jīng)濟學(xué)-高鴻業(yè)-筆記
- 幼兒園美術(shù)教育研究策略國內(nèi)外
- 2024屆河南省五市高三第一次聯(lián)考英語試題及答案
- 孕婦學(xué)校品管圈課件
- 《愿望的實現(xiàn)》交流ppt課件2
評論
0/150
提交評論