資源描述:
《Java容器類分析之List ArrayList Vector》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、Java容器類分析之ListArrayListVectorList是接口,聲明了各個方法,不多說。且看ArrayList類。ArrayList類的成員變量有Object[]elementData,intsize;其中elementData數(shù)組用來存儲加入到ArrayList的對象,size為列表中實際的對象數(shù)目。ArrayList類不是線程安全的。Vector與ArrayList的實現(xiàn)基本相同,只是Vector類是線程安全的,其方法都帶有synchronized關(guān)鍵字,如果不考慮線程同步的話,ArrayList性能要好一些。當(dāng)前它們內(nèi)部實現(xiàn)原理
2、都是用到對象數(shù)組來實現(xiàn),如果元素數(shù)目確定,直接用數(shù)組效率最高。簡單的用法:(后面是數(shù)據(jù)打印結(jié)果)1.public?class?ListDemo?{?2.?3.????/**?4.?????*?@param?args?5.?????*/?6.????public?static?void?main(String[]?args)?{?7.????????List?list?=?new?ArrayList();?8.????????String[]?strArr?=?new?String[3];?9.????????bo
3、olean?ret?=?list.add("haha");?10.????????list.add(new?String("aa"));?11.????????list.add(null);??12.????????System.out.println(list.size());//3?13.????????System.out.println(ret);//true?14.????????System.out.println(list);//[haha,?aa,?null]?15.????????System.out.println(strA
4、rr);//[Ljava.lang.String;@1fee6fc?16.????????System.out.println(strArr.getClass().getName());//[Ljava.lang.String;?17.????????System.out.println(list.indexOf("aa"));//1?18.????????System.out.println(list.indexOf(null));//2?19.????????String?str?=?list.set(1,?"ee");?20.??????
5、??System.out.println(str);//aa?21.????????System.out.println(list);//[haha,?ee,?null]?1.????????String?remove?=?list.remove(0);?2.????????System.out.println(remove);//haha?3.????????System.out.println(list);//[ee,?null]?4.????????boolean?result?=?list.remove("ff");?5.???????
6、?System.out.println(result);//false?6.????????result?=?list.remove("ee");?7.????????System.out.println(result);//true?8.????????System.out.println(list);//[null]?9.????}?10.?11.}?1.public?ArrayList()?{?2.????this(10);?3.????}?4.?public?ArrayList(int?initialCapacity)?{?5.????
7、super();?6.????????????if?(initialCapacity?0)?7.?????????????????throw?new?IllegalArgumentException("Illegal?Capacity:?"+?initialCapacity);?8.????this.elementData?=?new?Object[initialCapacity];?9.????}?10.???public?boolean?add(E?e)?{?11.????ensureCapacity(size?+?1);??//?In
8、crements?modCount!!?12.????elementData[size++]?=?e;?13.????return?true;?14.