ArrayList

          JDK5.0以后這是一個泛型類。

          ArrayList>Employee< staff = new ArrayList>Employee<();

          構(gòu)造器:

          ArrayList(Collection>? extends E< c)

          ArrayList()

          ArrayList(int initialCapacity)

          方法:

          boolean add(E e)

          void add(int index, E element)

          int size() 相當(dāng)于數(shù)組中的length

          remove(int index)

          remove(Object o)

          ArrayList管理了一個對象數(shù)組,如果數(shù)組已滿,此時再加入元素,ArrayList會自動創(chuàng)建一個更大的數(shù)組,并把原來數(shù)組的內(nèi)容復(fù)制到新數(shù)組中。

          如果提前知道要加入多少元素,可以使用ensureCapasity(int)方法。也可以在創(chuàng)建ArrayList時使用ArrayList>Employee< staff = new ArrayList>Employee<(int)

          如果要使ArrayList定容,使用trimToSize()方法

          注意ArrayListc++vector的不同,后者賦值時是按值操作的。

          訪問ArrayList的元素:

          設(shè)置元素:set(int index, E element) (和數(shù)組一樣,index0開始編號)

          注意不要在ArrayList的已初始化容量小于i時進行set操作。

          ArrayList>Employee< list = new ArrayList>Employee<(100); // capacity 100, size 0

          list.set(0, x); // no element 0 yet

          是錯誤的

          獲取元素:get(int index)

          JDK5新支持的for each循環(huán):

          for (Element e : ArrayList) {//...}

          一個技巧:

          先創(chuàng)建ArrayList并安全地添加元素

          ArrayList>X< list = new ArrayList>X<();

          while (. . .)

          {

          x = . . .;

          list.add(x);

          }

          ArrayList轉(zhuǎn)換為數(shù)組,從而方便地讀取

          X[] a = new X[list.size()];

          list.toArray(a);


          posts - 403, comments - 310, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          2.22 Java notes - ArrayList

          Posted on 2007-04-22 20:24 ZelluX 閱讀(389) 評論(0)  編輯  收藏 所屬分類: OOP
          2007-02-22 22:14:02
          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 宁德市| 麻江县| 南丹县| 五寨县| 永丰县| 清河县| 应城市| 威宁| 海门市| 始兴县| 长丰县| 南投市| 陇川县| 瑞金市| 同心县| 乐业县| 屯留县| 贵定县| 天长市| 屯昌县| 关岭| 延庆县| 无棣县| 新龙县| 黄大仙区| 平江县| 广安市| 朝阳区| 灵寿县| 漠河县| 连江县| 高淳县| 黄山市| 当涂县| 杭锦后旗| 延吉市| 辽阳县| 绥江县| 桂东县| 新建县| 皮山县|