欢迎来到天天文库
浏览记录
ID:59323068
大小:2.64 MB
页数:69页
时间:2020-09-20
《墨尔本大学java课程课件.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Chapter14GenericsandtheArrayListClassCopyright©2010PearsonAddison-Wesley.Allrightsreserved.IntroductiontoGenericsBeginningwithversion5.0,JavaallowsclassandmethoddefinitionsthatincludeparametersfortypesSuchdefinitionsarecalledgenericsGenericprogrammingwithatypeparameterenablescodetobewrittent
2、hatappliestoanyclass14-2Copyright©2010PearsonAddison-Wesley.Allrightsreserved.TheArrayListClassArrayListisaclassinthestandardJavalibrariesUnlikearrays,whichhaveafixedlengthoncetheyhavebeencreated,anArrayListisanobjectthatcangrowandshrinkwhileyourprogramisrunningIngeneral,anArrayListservesthes
3、amepurposeasanarray,exceptthatanArrayListcanchangelengthwhiletheprogramisrunning14-3Copyright©2010PearsonAddison-Wesley.Allrightsreserved.TheArrayListClassTheclassArrayListisimplementedusinganarrayasaprivateinstancevariableWhenthishiddenarrayisfull,anewlargerhiddenarrayiscreatedandthedataistr
4、ansferredtothisnewarray14-4Copyright©2010PearsonAddison-Wesley.Allrightsreserved.TheArrayListClassWhynotalwaysuseanArrayListinsteadofanarray?AnArrayListislessefficientthananarrayItdoesnothavetheconvenientsquarebracketnotationThebasetypeofanArrayListmustbeaclasstype(orotherreferencetype):itcan
5、notbeaprimitivetypeThislastpointislessofaproblemnowthatJavaprovidesautomaticboxingandunboxingofprimitives14-5Copyright©2010PearsonAddison-Wesley.Allrightsreserved.UsingtheArrayListClassInordertomakeuseoftheArrayListclass,itmustfirstbeimportedfromthepackagejava.utilAnArrayListiscreatedandnamed
6、inthesamewayasobjectofanyclass,exceptthatyouspecifythebasetypeasfollows:ArrayListaList=newArrayList();14-6Copyright©2010PearsonAddison-Wesley.Allrightsreserved.UsingtheArrayListClassAninitialcapacitycanbespecifiedwhencreatinganArrayListaswellThefollowingcodecreatesanArrayL
7、istthatstoresobjectsofthebasetypeStringwithaninitialcapacityof20itemsArrayListlist=newArrayList(20);SpecifyinganinitialcapacitydoesnotlimitthesizetowhichanArrayListcaneventuallygrowNotethatthebasetypeofanArrayListisspecifiedas
此文档下载收益归作者所有