|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
java是一种面向对象的编程语言,优点是可移植性比较高,最初设计时就是本着一次编写到处执行设计的。可以开发各种应用程序和游戏,不过速度没有c++快,所以一般是不用java来编写应用程序和电脑游戏。access1)DeclarationsandAccessControl
Objective1
Writecodethatdeclares,constructsandinitializesarraysofanybasetypeusinganyofthepermittedforms,bothfordeclarationandforinitialization.
1.ArraysareJavaobjects.(Anobjectisaclassinstanceoranarray.)andmaybeassignedtovariablesoftypeObject.AllmethodsofclassObjectmaybeinvokedonanarray.Ifyoucreateanarrayof5Strings,therewillbe6objectscreated.
2.Arraysshouldbe
1.Declared.(int[]a;Stringb[];Object[]c;Sizeshouldnotbespecifiednow)
2.Allocated(constructed).(a=newint[10];c=newString[arraysize])
3.Initialized.for(inti=0;i<a.length;a[i++]=0)
3.Theabovethreecanbedoneinonestep.inta[]={1,2,3};orinta[]=newint[]{1,2,3};Butneverspecifythesizewiththenewstatement.
4.Javaarraysarestaticarrays.Sizehastobespecifiedatcompiletime.Array.lengthreturnsarray’ssize,cannotbechanged.(UseVectorsfordynamicpurposes).
5.Arraysizeisneverspecifiedwiththereferencevariable,itisalwaysmaintainedwiththearrayobject.Itismaintainedinarray.length,whichisafinalinstancevariable.Notethatarrayshavealengthfield(orproperty)notalength()method.WhenyoustarttouseStringsyouwillusethestring,lengthmethod,asins.length();
6.Anonymousarrayscanbecreatedandusedlikethis:newint[]{1,2,3}ornewint[10]
7.Arrayswithzeroelementscanbecreated.argsarraytothemainmethodwillbeazeroelementarrayifnocommandparametersarespecified.Inthiscaseargs.lengthis0.
8.Commaafterthelastinitializerinarraydeclarationisignored.
int[]i=newint[2]{5,10};//Wrong
inti[5]={1,2,3,4,5};//Wrong
int[]i[]={{},newint[]{}};//Correct
inti[][]={{1,2},newint[2]};//Correct
inti[]={1,2,3,4,};//Correct
inti[][]=newint[10][];//Correct,i.length=10.
int[]i,j[]==inti[],j[][];
9.Arrayindexesstartwith0.Indexisanintdatatype.
10.Squarebracketscancomeafterdatatypeorbefore/aftervariablename.Whitespacesarefine.Compilerjustignoresthem.
11.Arraysdeclaredevenasmembervariablesalsoneedtobeallocatedmemoryexplicitly.
staticinta[];
staticintb[]={1,2,3};
publicstaticvoidmain(Strings[]){
System.out.println(a[0]);//Throwsanullpointerexception
System.out.println(b[0]);//Thiscoderunsfine
System.out.println(a);//Prints‘null’
System.out.println(b);//PrintsastringwhichisreturnedbytoString
}
12.Oncedeclaredandallocated(evenforlocalarraysinsidemethods),arrayelementsareautomaticallyinitializedtothedefaultvalues.(0fornumericarrays,falseforboolean, forcharacterarrays,andnullforobjects).
13.Ifonlydeclared(notconstructed),memberarrayvariablesdefaulttonull,butlocalarrayvariableswillnotdefaulttonull(compileerror).
14.Javadoesn’tsupportmultidimensionalarraysformally,butitsupportsarraysofarrays.Fromthespecification-“Thenumberofbracketpairsindicatesthedepthofarraynesting.”Sothiscanperformasamultidimensionalarray.(nolimittolevelsofarraynesting)
15.Arraysmustbeindexedbyintvalues;short,byte,orcharvaluesmayalsobeusedasindexvaluesbecausetheyaresubjectedtounarynumericpromotionandbecomeintvalues.Anattempttoaccessanarraycomponentwithalongindexvalueresultsinacompile-timeerror.
16.Allarrayaccessesarecheckedatruntime;anattempttouseanindexthatislessthanzeroorgreaterthanorequaltothelengthofthearraycausesanArrayIndexOutOfBoundsExceptiontobethrown.
17.EveryarrayimplementstheinterfacesCloneableandjava.io.Serializable.
18.ArrayStoreException
IfanarrayvariablevhastypeA[],whereAisareferencetype,thenvcanholdareferencetoaninstanceofanyarraytypeB[],providedBcanbeassignedtoA.
Thus,theexample:
classPoint{intx,y;}
classColoredPointextendsPoint{intcolor;}
classTest{
publicstaticvoidmain(String[]args){
ColoredPoint[]cpa=newColoredPoint[10];
Point[]pa=cpa;
System.out.println(pa[1]==null);
try{
pa[0]=newPoint();
}catch(ArrayStoreExceptione){
System.out.println(e);
}
}
}
producestheoutput:
true
java.lang.ArrayStoreException
Testingwhetherpa[1]isnull,willnotresultinarun-timetypeerror.ThisisbecausetheelementofthearrayoftypeColoredPoint[]isaColoredPoint,andeveryColoredPointcanstandinforaPoint,sincePointisthesuperclassofColoredPoint.
Ontheotherhand,anassignmenttothearraypacanresultinarun-timeerror.Atcompiletime,anassignmenttoanelementofpaischeckedtomakesurethatthevalueassignedisaPoint.ButsincepaholdsareferencetoanarrayofColoredPoint,theassignmentisvalidonlyifthetypeofthevalueassignedatrun-timeis,morespecifically,aColoredPoint.ifnot,anArrayStoreExceptionisthrown.
19.EveryelementofanarraymustbeofthesametypeThetypeoftheelementsofanarrayisdecidedwhenthearrayisdeclared.Ifyouneedawayofstoringagroupofelementsofdifferenttypes,youcanusethecollectionclasses.
Java的桌面程序开发在java程序员里通常叫swing开发,主要用的swing包里的类开发的,也就是通常说的c/s架构开发 |
|